25

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.

Wouter J
  • 41,455
  • 15
  • 107
  • 112
nishchay2192
  • 353
  • 1
  • 3
  • 6

2 Answers2

16

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).

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
12

From man scanf in my Linux box:

A directive is one of the following:

A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

BTW, %d is also a directive.

So your "%d\n" has two directives, the first one reads the number and the second one... well reads any amount of white space, including your end-of-lines. You have to type any non-white space character to make it stop.

Community
  • 1
  • 1
rodrigo
  • 94,151
  • 12
  • 143
  • 190