Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c - What does a number between '%' and format specifier mean in scanf ?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...