I know the options used in format specifier for printf()
, but I am totally clueless about what something like %3d
could mean, as in the code below.
scanf("%3d %3d",&num1,&num2);
To be general, What does the number between %
and format specifier
indicate in a scanf statement.
Isn't scanf()
meant simply to receive input and store it in the addresses specified in the argument?
You need to look at the fine documentation.
Basically, a number between the %
and the conversion specifier indicates the maximum field width. The conversion will stop after the specified number of characters has been processed.
This can be handy to "cut apart" a sequence of digits into multiple individual numbers, like so:
const char *date = "20130426";
int year, month, day;
if(sscanf(date, "%4d %2d %2d", &year, &month, &day) == 3)
print("the date is %4d-%02d-%02d\n", year, month, day);
Note that whitespace in the format string matches any sequence of white space (including none) in the input, so the above works even though the input string (date
) doesn't contain any whitespace. Using whitespace in the format string can help make it more readable.
In response to your stdin
comment, the sscanf()
function doesn't know (or care) where the string it operates upon comes from, it's just a string. So yes, you can call it on data read from stdin
, from a file, created on the fly elsewhere in the program, received over the network, or any other way.