Using "\n" in scanf() in C

nishchay2192 picture nishchay2192 · Mar 16, 2013 · Viewed 21.5k times · Source

I mistakenly used scanf("%d\n",&val); in one of my programmes, I could not understand the behavior, the function showed.

int main(){
    int val;
    scanf("%d\n", &val);
    printf("%d\n", val);
    return 0;
}

Now the program required 2 integer inputs, and prints the first input that was entered. What difference should that extra \n brings?

I tried to search but couldn't find the answer, even through manual of scanf.

Answer

Daniel Fischer picture Daniel Fischer · Mar 16, 2013

An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input. So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream (e.g. when the input is redirected from a file and its end is reached, or after you closed stdin with Ctrl-D).