Stelios Papamichail
Stelios Papamichail

Reputation: 1268

scanf keeps \n character in the buffer

I'm new to C and i am trying to read 6 integers with scanf .However, i noticed and read that scanf leaves the \n char (which i have in my format string) in the buffer thus "reading" an extra input from the user.On various stack posts i read that this can be simply solved by adding a white space in front of the %d format (e.g: scanf(" %d\n",&var);but that doesn't work for me.What should i do and why does this happen?

Here's my current code:

#include <stdio.h>

int main(void) {
    int A[2][3] = {};
    int B[3][2] = {};
    int i,j;
    for(i=0; i < 2;i++) {
        for(j=0; j < 3;j++) {
            scanf(" %d\n", &A[i][j]);
            getchar();
        }
    }
    return 0;
}

Upvotes: 1

Views: 529

Answers (2)

dbush
dbush

Reputation: 223689

The \n in your format string is actually causing a problem. After reading an integer, the \n in the format string matches any number of whitespace characters, so the function won't return until some non-whitespace character is inputted.

Change the format string as follows:

scanf("%d", &A[i][j]);

the %d format specifier implicitly discards any leading whitespace characters, so no need for a leading space (that's only needed for %c).

Upvotes: 2

mch
mch

Reputation: 9804

%d ignores whitespaces before the number. You only have this problem when you read a number with %d (which leaves the newline in the buffer) and want to read a char with %c afterwards. There you have to put a whitespace before the %c, so that it will ignore the newline in the buffer.

When you want to read numbers only you can use scanf("%d", &var);.

Upvotes: 1

Related Questions