Why input (newline) won't exit scanf?

Here's the program:

#include "stdio.h"

int main()
{
    int minx, x, y, z;

    printf("Enter four ints: ");
    scanf( "%i %i %i %i", &minx, &x, &y, &z);

    printf("You wrote: %d %d %d %d", minx, x, y, z);
}

      

Tell me if I enter the following: 1 2 3 4 (then press enter). scanf()

starts and reads the input buffer = 1 (space) 2 (space) 3 (space) 4 (space) (\ n) it reads up to (\ n) and \ n will stay in the buffer.

If I enter the following: 1 (then press enter) 2 (then press enter) 3 (then press enter) 4 (then press enter). scanf()

starts and reads input buffer = 1 (\ n) 2 (\ n) 3 (\ n) 4 (\ n) (\ n).

In these two cases, it scanf()

skips a newline, a space, and tries to read int

.

But if I enter 1 (then press enter) (then press enter) ... scanf()

it never starts if I keep pressing enter.

My question is what triggers scanf()

? Will it only work after it knows that all the correct ones have been %d

buffered and then executed if the user presses enter?

+3


source to share


2 answers


Because it scanf()

ignores whitespace and whitespace contains newlines.

scanf()

treats the four numbers the same way each time: skipping the space, then looking at the candidate sequence that looks like a number (so the signs and numbers), and stops reading the first character, which cannot be part of the candidate sequence; it then converts the sequence of candidates (overflow behavior, etc. undefined). If you typed a space after 4

(not just newlines), the space and newline will still wait for the next read. If there is no room, then the new line will wait to be read.



If you typed a non-numeric character (punctuation or letter), it scanf()

will return with an error (or less than four numbers will be converted if the letter is not after the fourth number).

When you enter a single number followed by an arbitrary number of newlines, you simply skip the space scanf()

. It will not stop until it receives an EOF (read with a null byte) or a read error (or a conversion error such as a letter or punctuation character instead of a number).

+4


source


i.e. the expected behavior of scanf From the c99 standard:

The conversion specification is performed in the following steps: - Input space characters (as specified in the isspace function) are skipped unless the specification includes the '[', 'c', or 'n' specifier.



it tokenizes seperator characters (white space on newline, etc.) the last newline is part of the tokenization. Otherwise, how does she know when the integer runs out ?: D

I think this solves your question? I'm not sure. Hope it helps

+1


source







All Articles