问题
I am trying to input two characters from the user t
number of times. Here is my code :
int main()
{
int t;
scanf("%d",&t);
char a,b;
for(i=0; i<t; i++)
{
printf("enter a: ");
scanf("%c",&a);
printf("enter b:");
scanf("%c",&b);
}
return 0;
}
Strangely the output the very first time is:
enter a:
enter b:
That is, the code doesn't wait for the value of a
.
回答1:
The problem is that scanf("%d", &t)
leaves a newline in the input buffer, which is only consumed by scanf("%c", &a)
(and hence a
is assigned a newline character). You have to consume the newline with getchar();
.
Another approach is to add a space in the scanf()
format specifier to ignore leading whitespace characters (this includes newline). Example:
for(i=0; i<t; i++)
{
printf("enter a: ");
scanf(" %c",&a);
printf("enter b: ");
scanf(" %c",&b);
}
If you prefer using getchar()
to consume newlines, you'd have to do something like this:
for(i=0; i<t; i++)
{
getchar();
printf("enter a: ");
scanf("%c",&a);
getchar();
printf("enter b:");
scanf("%c",&b);
}
I personally consider the former approach superior, because it ignores any arbitrary number of whitespaces, whereas getchar()
just consumes one.
回答2:
By seeing your code it's perfect it should read T times A and B but it replaces A and B every time the for each loop.
Use array or hash table to store effectively
回答3:
Some formats used with scanf
makes a newline trimmed from stdin
but others don't. Reading using "%d"
falls into latter category. You need to read a newline '\n'
before reading into
scanf("%c", &a);
来源:https://stackoverflow.com/questions/24099976/read-two-characters-consecutively-using-scanf-in-c