Hi
#include<stdio.h>
main()
{
char s[]="Taiwan University.";
float a;
scanf("%f",&a);
printf("%f",a);
printf("input string:");
gets(s);
puts("%s",s);
}
After compiled by Visual Studio, the above program can input a.
But after it shows a, then I cannot enter s string.
Why?
Mike
When you type in your floating point number (3.14159, for example) and
hit Enter, the input stream looks like this:
{'3','.','1','4','1','5','9',\n}
After the call to scanf(), the newline character is still left in the
input stream:
{\n}
because scanf() with the %f conversion specifier stops reading at the
first character that isn't part of a valid floating-point constant.
gets() reads up to the next newline character; since there's already a
newline character in the input stream left over from the last input
operation, it returns immediately.
There are two ways around this. The easy way is to stick a getchar()
after the scanf() to consume the newline. A somewhat more involved
(but ultimately safer) way is to read your floating-point number in as
a string using fgets() (*NOT* gets()), and then convert using sscanf()
or strtod().
Do not use gets(); it *WILL* introduce a point of failure in your
code. Use fgets() instead:
fgets(s, sizeof s, stdin);
Unlike gets(), fgets() writes the trailing newline to your buffer.