I'm using MinGW on windows 7 to compile C files.
My problem is a strange behaviour with scanf()
to read double
s from user input.
My code:
int main() {
double radius = 0;
double pi = 3.14159;
scanf("%lf \n", &radius); // after the input, it continues waiting...
radius = ((radius * radius) * pi);
printf("A=%.4lf\n", radius);
return 0;
}
When I run this program it's necessary input a value, let's suppose 100.64
, the normal behaviour is press enter and the program should continue and show the result, but the program stays waiting for more input. If I type 0 and press enter again, the program continues normal.
>area.exe
100.64 <-- doesn't proceed after press enter
0 <-- needs input another value, then press enter
A=31819.3103 <-- the result
Why scanf doesn't proceed with the first input? Why it needs more?
Obs: in my Linux this doesn't occur.
gcc --version
gcc (tdm64-1) 4.9.2
You have the same solution for a little bit different problem (just in type of variable)
Why does scanf ask for input twice, but just in the first loop iteration only?
When you include the whitespace in the scanf
The program will wait until you enter a blank space or any other value in it, so the program will continue as normal, but the blank space or any value that you entered will not be used anyway.
In your code, change
to
Otherwise, with a format string having
whitespace
,scanf()
will behave as below (quoted fromC11
, chapter§7.21.6.2
, paragraph 5)So, to provide the "non-white-space character" to end the scanning, you need to input a
0
(basically, a non-whitespace character).Please check the man page for more details.