Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "\n" in scanf() in C [duplicate]

Tags:

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.

like image 944
nishchay2192 Avatar asked Mar 15 '13 23:03

nishchay2192


People also ask

What happens if we use \n in scanf?

An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input.

Does scanf skip newline?

scanf(" %c", &ch); The leading space tells scanf() to skip any whitespace characters (including newline) before reading the next character, resulting in the same behavior as with the other format specifiers.

Can we write n in scanf?

In C, %n is a special format specifier. In the case of printf() function the %n assign the number of characters printed by printf(). When we use the %n specifier in scanf() it will assign the number of characters read by the scanf() function until it occurs.

How do you scanf doubles?

To read a double, supply scanf with a format string containing the conversion specification %lf (that's a lower case L, not a one), and include a double variable preceded by an ampersand as the second parameter.


2 Answers

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.

like image 41
rodrigo Avatar answered Oct 06 '22 19:10

rodrigo


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

like image 91
Daniel Fischer Avatar answered Oct 06 '22 18:10

Daniel Fischer