I'm coming off a 2-3 year hiatus from programming in C and trying to re-learn the language. Unfortunately, I have source from before, but no notes to learn from.
I'm having a problem with reading in a single character using scanf. I've also tried using getc. Basically, I have a little program like this one below:
Code:
int main(void)
{
char myChar;
unsigned char flag = 0;
while (flag == 0)
{
printf("Enter character: ");
scanf("%c",&myChar);
printf("You entered '%c'.\n\n",myChar);
if (myChar == 'q')
flag = 1;
}
return (0);
}
Now, I have two problems with this code:
1) When you enter a single character, since the newline character is still in the input stream, the next time the loop comes around, '\n' is passed to scanf, which produces this result:
Code:
Enter Character: J
You entered 'J'
Enter Character: You entered '
'
Enter Character:
... not what I want. So how do I handle the newline character in this situation? I've tried this with getc as well and have the same results.
2) Besides the newline character, if the user enters more than one letter at the prompt, all the letters get processed through the loop. So you get something like:
Code:
Enter Character: hello
You entered 'h'
Enter Character: You entered 'e'
Enter Character: You entered 'l'
Enter Character: You entered 'l'
Enter Character: You entered 'o'
Enter Character: You entered '
'
Enter Character:
So I assume the two problems are related somehow, but I'm completely stumped as to how to resolve the problem. Looking back through my old source code I see things like:
Code:
myChar = getc(stdin);
fflush(stdin);
... which apparently worked (again, it was a while back, I can't remember for sure). But when I compile the same code on my system now, it fails. Doesn't make sense since I thought fflush was only for output buffers and not input ones.
Can anyone help me out understanding all this again? Anyone know of any good online 'C refreshers' I can visit?
Thanks,
- coredumped.