Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

All forms of formatted scanf() in C

  • Difficulty Level : Basic
  • Last Updated : 23 Sep, 2021

C language has standard libraries that allow input and output in a program. The stdio.h or standard input-output library in C has methods for input and output.

scanf(): The scanf() method n C Language, reads the value from the console as per the type specified. It returns an integer type, the number of successfully matched and assigned input items.

We provide nothing but the best curated videos and practice problems for our students. Check out the C Foundation Course and master the C language from basic to advanced level. Wait no more, start learning today!

Syntax:

int scanf(const char*format, arg1, agr2, arg3, ...);

The scanf() function reads characters from the standard input(keyboard), interprets them according to the conversion specification in format(const char*format), and stores the result through the matching argument list (arg1, arg2, arg3, …). Arguments list each of which must be a pointer indicates where the corresponding converted input should be stored. It stops when-



  • It exhausts its format string (all inputs taken)
  • When some input fails to match the control specification.

Program 1: Read the two integer values using formatted input scanf():

C




// C program to implement the above idea
#include <stdio.h>
  
// Driver Code
int main()
{
    int a, b, c;
    c = scanf("%d %d", &a, &b);
    printf("Number of successful "
           "inputs read : %d",
           c);
  
    return 0;
}

Output:

Reading successful inputs:

Successful Inputs

Explanation: Since both the input values are integers and the format specifier in the scanf() function is ‘%d’, thus input values are read and scanf() function returns the number of values read.

Reading unsuccessful Inputs:

Unsuccessful inputs



Explanation: As here the second argument entered is a string and is not matching to the format specifier ‘%d’ that is an integer so scanf will not store the value into the second argument and will return 1, as only 1 input is successfully read, and the scanf() will terminate here.

Note: Since the argument list in scanf() must be the pointer that is why it is written &a, &b (&variablename gives the address of the variable). If ‘&’ is missed from the scanf() function then the program will show undefined behavior and the compiler will not show an error.

Program 2: Reading String Using scanf:

Below is the C program to read a string using formatted input scanf():

C




// C program to implement the above idea
#include <stdio.h>
  
// Driver Code
int main()
{
    // Declaring character array
    char str[10];
  
    // & is not used
    scanf("%s", str);
    printf("%s", str);
    return 0;
}

Output:

Read string

Note: The & is not used in the case of string reading because the array name is a pointer to the first element (str[0]). One more point to note here is that “%s” does not read whitespace characters (blank space, newline, etc). Below is the output example for the same:

Explanation: As the scanf() encounters blank space or newline it starts reading next argument if available. that is why only Hello is read here and not World.



Format String: If the syntax of scanf() is observed carefully, then it has two parts:

  1. Format string.
  2. The number of arguments.

Everything in double-quotes is called a format string and everything after comma(, ) are the matching arguments. The format string may contain-

  • Blanks or tabs are ignored.
  • Ordinary characters (not %), which are expected to match the next non-whitespace character of the input stream.
  • A conversion specification, consisting of the following:
    1. Character %.
    2. An optional assignment suppression character  *.
    3. An optional number specifying a maximum field width.
    4. An optional h, l, or L indicating the width of the target.
    5. A conversion character.

A conversion specification starts with a compulsory % character and ends with a compulsory conversion character. For Example- d, s, f, i, etc. Any point 2 – 4 (optional) if needed to add should be added in the order in between % and a conversion character.

Let’s understand all these points with an example:

Example 1: Read time in the format 11: PM (an integer value followed by a colon(:) and a string).

Read time

Note: In the above example (:) is not stored in any variable it is just to match the input format given.

Program 3: Below is the program to read the value but do not store in a variable:

C




// C program to implement the above idea
#include <stdio.h>
  
// Driver Code
int main()
{
    int x = 4;
  
    // Read but do not store
    // in x
    scanf("%*d", &x);
  
    // Print initialized value
    printf("%d", x);
  
    return 0;
}

Output



Output

Explanation: Output is 4, not 10 because the assignment suppression character “*” is used, on using this, the input field is skipped and no assignment is made.

Program 4: Below is the program to read a string but a maximum of 4 characters is allowed:

C




// C program to implement the above idea
#include <stdio.h>
  
// Driver Code
int main()
{
    // Array of 10 character elements
    char str[10];
  
    // Can read maximum four characters
    scanf("%4s", str);
    printf("%s", str);
    return 0;
}

Output

Output

Explanation: Maximum of four characters can only be read but in the input, the fifth character o is given which is skipped.

Program 5: Read an integer but its size should be long or short:

C




// C program to implement the above idea
#include <stdio.h>
  
// Driver code
int main()
{
    // For reading long int
    long int x;
    scanf("%ld", &x);
    printf("%ld", x);
  
    // For reading short int
    short int y;
    scanf("%hd", &y);
    printf("%hd", y);
    return 0;
}

Output:



Output

Conversion Character:

Let’s have a look at the full list of conversion characters:

Conversion CharacterInput Data
dDecimal integer (int*). For Example 10, 20.
Note: 10, 010 both means 10.
i

Integer (int*). The integer may be in octal (leading 0(zero)) or hexadecimal leading 0x or 0X  
Note:

  • 010 means 8 because it starts with 0 so it is octal number and 10(octal) = 8(decimal).
  • 10 means 10 (because no leading 0(zero) or leading 0x or 0X.
  • 0x10 means 16 because it starts with 0x so it hexadecimal number and 10(hexadecimal) =16(decimal).
o

Octal integer (with 0 or without leading zero) (int *)
Note: Any number entered will be treated as an octal number.

  • 10 means 8
  • 010 also means 8
uAn unsigned decimal integer (unsigned int*).
Note: It reads only positive number if you enter any negative number MSB(most significant bit will not be treated as a sign bit and will be taken for calculation )
x

Hexadecimal integer (with or without leading 0x or 0X) (int *).
Note: Any number entered will be treated as a hexadecimal number

  • 10 means 16.
  • 0x10 also means 16.
cCharacters( char*).The next input characters(default 1) are placed at the indicated spot the normal skip over white space is suppressed means it can read white space characters. To read the next non-whitespace character use 1s.
s

Character string (not quoted) (char*), use for reading the string.
Note:

  • White space characters cannot be read.
  • The size of the variable should be 1 extra character large as at the end NULL(‘\0’) is appended.
e, f, gFloating-point number with optional sign, optional decimal point & optional exponent (float*).
%Literal%, no assignment is made.

Reading Input From Other String: sscanf()

In the previous examples, the input was read from the keyboard. Let’s have a look at the example of how to read input from other strings. Below is the C program to implement the above concept:

C




// C program to implement the above concept
#include <stdio.h>
  
// Driver code
int main()
{
    // String from which input
    // to be read
    char str[] = "11:pm";
    int x;
    char time[3];
    sscanf(str, "%d:%s", &x, time);
    printf("%d:%s", x, time);
  
    return 0;
}
Output
11:pm



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!