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.

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.