问题
int main()
{
int r, c;
r = getchar();
c = getchar();
putchar(r);
putchar(c);
printf("\n");
return(0);
}
After it reads in r, the program outputs r and quits. I want it to ask for c and input it but how come it doesnt do that?
回答1:
Are you entering the characters on the same line, or on 2 lines?
getchar() will wait until you press enter, and then start parsing the characters. If you have entered 2 characters on 2 different lines, it will read the first character and then the \n character.
What I mean is, the following input:
a
b
is equivalent to "a\nb".
getchar() will grab the \n instead of b, and print a\n\n.
You want to type both characters, and only then hit enter.
回答2:
You're probably typing X + Enter. The first getchar() reads the character X, and the second getchar() reads a newline generated when you press Enter. Type both your characters without pressing Enter.
来源:https://stackoverflow.com/questions/5609267/i-want-to-getchar-twice-but-i-cant