getchar() only calling every other time

旧时模样 提交于 2019-12-12 02:55:06

问题


While using Ch Standard Interpreter, getchar() only runs every other line.

C:/> char a = getchar();
C:/> char b = getchar();
b
C:/> char c = getchar();
C:/> char d = getchar();
d

I have the same issue when using scanf("%c", &a) instead; in Vim the statement is skipped.

printf("\nType of Something\nA for SomethingA\nB for SomethingB "
        "\nC for SomethingC\n\nSelect (A,B,C) > ");
char letter = getchar(); // This statement gets skipped
return 0;

回答1:


When you type "A" on the keyboard, you first press "A", and then you press "ENTER", right? So getchar() or scanf("%c", ....) gets two characters to read: "A", and the newline character from the "ENTER" key.

If you use your code in a loop, or just repeatedly, the first getchar() will read the newline character from the previous input.



来源:https://stackoverflow.com/questions/9552697/getchar-only-calling-every-other-time

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