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
.
An '\n' - or any whitespace character - in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input.
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With