Using scanf in for loop

Here is my c code:

int main() { int a; for (int i = 0; i < 3; i++) scanf("%d ", &a); return 0; } 

When I enter things like 1 2 3 , he will ask me to enter more, and I need to enter something not.

However, when I change it to (or another thing is not ' ' )

 scanf("%d !", &a); 

and enter 1 ! 2! 3! 1 ! 2! 3! , it will not ask for more input.

+6
source share
3 answers

Final space in scanf("%d ", &a); instructs scanf consume all spaces after the number. It will read with stdin until you type something that is not white. Simplify the format as follows:

 scanf("%d", &a); 

scanf will still ignore the space before the numbers.

And vice versa, the format is "%d !" consumes any space after number and one ! . It stops scanning when it receives this character, or another space character that it leaves in the input stream. You cannot indicate from the return value whether it matches ! or not.

scanf very awkward, it is very difficult to use correctly. It is often better to read the input line with fgets() and parse it with sscanf() or even simpler functions like strtol() , strspn() or strcspn() .

+6
source
 scanf("%d", &a); 

That should do the job.

0
source

Basically, scanf() consumes stdin input as much as matches its pattern. If you pass "%d" as a template, it will stop reading input after an integer is found. However, if you feed it using "%dx" , for example, it matches all integers followed by the 'x' character.

More details:

Your template string can have the following characters:

  • Space character: the function will read and ignore any whitespace characters that appear before the next non-whitespace character (whitespace characters include spaces, newlines and tabs - see isspace). A single space in the format string checks for any number of whitespace characters extracted from the stream (including none).

  • Character without spaces, except for the format specifier (%): Any character that is not a space character (space, newline or tab) or a part of the format specifier (which begins with the% character) forces the function to read the next character from the stream, compare it with this character without spaces, and if it matches, it is discarded, and the function continues with the next character format. If the character does not match, the function does not work, returns and leaves the subsequent characters of the stream unread.

  • Format specifiers : The sequence formed by the initial percent sign (%) indicates the format specifier, which is used to indicate the type and format of the data to be extracted from the stream and stored in places indicated by additional arguments.

Source: http://www.cplusplus.com/reference/cstdio/scanf/

0
source

All Articles