Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - scanf() curious behaviour!

I recently stumbled upon a curious case(atleast for me, since I hadn't encountered this before)..Consider the simple code below:-

int x;
scanf("%d",&x);
printf("%d",x);

The above code takes a normal integer input and displays the result as expected..

Now, if I modify the above code to the following:-

int x;
scanf("%d ",&x);//notice the extra space after %d
printf("%d",x);

This takes in another additional input before it gives the result of the printf statement.. I don't understand why a space results in change of behaviour of the scanf().. Can anyone explain this to me....

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

From http://beej.us/guide/bgc/output/html/multipage/scanf.html:

The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list.

The format string is very similar to that in printf() in that you can tell it to read a "%d", for instance for an int. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

What's happening is scanf is pattern matching the format string (kind of like a regular expression). scanf keeps consumes text from standard input (e.g. the console) until the entire pattern is matched.

In your second example, scanf reads in a number and stores it in x. But it has not yet reached the end of the format string -- there is still a space character left. So scanf reads additional whitespace character(s) from standard input in order to (try to) match it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...