You ARE wrong.
First, read this:
http://faq.cprogramming.com/cgi-bin/sma ... 1043284351
The behaviour of flushing an
input buffer is undefined... and thus it doesn't do the same on all systems.
Second, consider the following code:
Code: Select all
[misof@elvander]:~/Temp/delme$ cat a.c
#include <stdio.h>
int main(void)
{
char c1,c2;
printf("char1: ");scanf("%c", &c1);
printf("char2: ");scanf("%c", &c2);
printf("both chars: %c%c\n",c1,c2);
return 0;
}
[misof@elvander]:~/Temp/delme$ gcc a.c
[misof@elvander]:~/Temp/delme$ echo -e "ab\n" | ./a.out
char1: char2: both chars: ab
[misof@elvander]:~/Temp/delme$ echo -e "a\nb\n" | ./a.out
char1: char2: both chars: a
[misof@elvander]:~/Temp/delme$ vim a.c
[misof@elvander]:~/Temp/delme$ cat a.c
#include <stdio.h>
int main(void)
{
char c1,c2;
printf("char1: ");scanf("%c", &c1);
fflush(stdin);
printf("char2: ");scanf("%c", &c2);
printf("both chars: %c%c\n",c1,c2);
return 0;
}
[misof@elvander]:~/Temp/delme$ gcc a.c
[misof@elvander]:~/Temp/delme$ ./a.out
char1: a
char2: both chars: a
[misof@elvander]:~/Temp/delme$ vim a.c
[misof@elvander]:~/Temp/delme$ cat a.c
#include <stdio.h>
int main(void)
{
char c1,c2;
printf("char1: ");scanf(" %c", &c1);
printf("char2: ");scanf(" %c", &c2);
printf("both chars: %c%c\n",c1,c2);
return 0;
}
[misof@elvander]:~/Temp/delme$ gcc a.c
[misof@elvander]:~/Temp/delme$ echo -e "a\nb\n" | ./a.out
char1: char2: both chars: ab
The first example is your original program. If the input contains two consecutive chars, everything works as planned. However, most probably you are entering your input as a<Return>b<Return>. This is what the second run does. Now the first scanf reads the "a", the second one reads the linefeed (or carriage return on other systems). This is what you probably refer to as "doesn't work".
On Linux (i.e. also here on the UVa), your modified code does exactly the same.
The correct way of getting the intended result is to understand how scanf() handles whitespace... and how input buffers work. If you run the program interactively, everything you type is sent to the program only
after you press <Return>. Thus you have to press <Return>
before you see the second message. Now, scanf("%c",...) reads the next character from the input buffer, be it a space, an end of line, whatever.
Note that in the third example a space is added in the format string before the "%c". A space in the format string says to scanf: "skip all the whitespace on the current position". Thus, when reading the next char, my scanf first skips all spaces, tabs, linefeeds, etc. and reads the first non-blank character. This is probably what you had in mind.