Thursday, February 11, 2016

Scanf Format Specifier

The above mapping of data types and corresponding format specifiers is also applicable to scanffunction. The %c format specifier is used to read a single character from the standard input, %sspecifier allows to read a string with a whitespace character as terminating character (space, line feed, carriage return etc.) and similar with other datatypes.
There is a difference in the use of gets and scanf with %s specifier. If you use scanf, it will read a string from input until a whitespace character is read. But gets will read a string until a newline character (\n) is reached. So if you use scanf("%s", line), where the line is a character array, and your input is a string "Nice C tutorial", after execution of this this statement you will get string "Nice" in the variable line. Because "Nice" is followed by a whitespace character (blank space). But using gets will populate the variable line with the whole string.
We can also specify maximum field width in the scanf. It is done by adding a number after % and before the specifier to limit the width of the input. Let's take a look at it with the help of an example,
  1. #include <stdio.h>
  2.  
  3. int main(void) {
  4. int a;
  5. printf("Enter number: ");
  6. scanf("%5d", &a);
  7. printf("Formatted number is: %d", a);
  8. return 0;
  9. }
  10.  
  11. Output:
  12. Enter number: 123456
  13. Formatted number is: 12345
In the above program, the format specifier used with scanf statement is %5d. This means, only the first 5 characters will be read into the variable. So the input '123456' is trimmed down to '12345'.
This can be applied to printf as well. But the result is quite different. If a variable has the value '123' and you use %5d in a printf statement, you will get 5 characters as output with leading two blank space and then three digit, but if you use %2d it will print all 3 digits.

No comments: