i want to getchar twice but i cant

随声附和 提交于 2019-12-31 03:04:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!