Rikka
Rikka

Reputation: 471

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 input things like 1 2 3, it will ask me to input more, and I need to input something not ' '.

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

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

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

Upvotes: 6

Views: 217

Answers (3)

frogatto
frogatto

Reputation: 29287

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

More Details:

Your pattern string could have the following characters:

  • Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

  • Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

  • Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments.

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

Upvotes: 0

chqrlie
chqrlie

Reputation: 145317

The final space in scanf("%d ", &a); instructs scanf to consume all white space following the number. It will keep reading from stdin until you type something that is not white space. Simplify the format this way:

scanf("%d", &a);

scanf will still ignore white space before the numbers.

Conversely, the format "%d !" consumes any white space following the number and a single !. It stops scanning when it gets this character, or another non space character which it leaves in the input stream. You cannot tell from the return value whether it matched the ! or not.

scanf is very clunky, it is very difficult to use it correctly. It is often better to read a line of input with fgets() and parse that with sscanf() or even simpler functions such as strtol(), strspn() or strcspn().

Upvotes: 6

Tony Tannous
Tony Tannous

Reputation: 473

scanf("%d", &a); 

This should do the job.

Upvotes: 0

Related Questions