All forms of formatted scanf() in C

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.
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 Codeint 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:
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:
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 Codeint main(){    // Declaring character array    char str[10];      // & is not used    scanf("%s", str);    printf("%s", str);    return 0;}
Output:
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:
Format string.The number of arguments.
Format string.
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:Character %.An optional assignment suppression character  *.An optional number specifying a maximum field width.An optional h, l, or L indicating the width of the target.A conversion character.
Character %.An optional assignment suppression character  *.An optional number specifying a maximum field width.An optional h, l, or L indicating the width of the target.A conversion character.
Character %.
An optional assignment suppression character  *.
An optional number specifying a maximum field width.
An optional h, l, or L indicating the width of the target.
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).
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 Codeint main(){    int x = 4;      // Read but do not store    // in x    scanf("%*d", &x);      // Print initialized value    printf("%d", x);      return 0;}
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 Codeint main(){    // Array of 10 character elements    char str[10];      // Can read maximum four characters    scanf("%4s", str);    printf("%s", str);    return 0;}
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 codeint 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:
Conversion Character:
Let’s have a look at the full list of conversion characters:
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).
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
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.
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.
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 codeint 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;}
11:pm
C Language
C Programs
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses