为什么代码偶数次直接获取到空数据?我不知道发生了什么事。
非常感谢。
#include <stdio.h>
#pragma warning(disable : 4996)
void main() {
int f, a = 10, b = 20;
for (int i = 0; i < 5; i++)
{
char ch;
ch = getchar();
printf("ch = %c\n", ch);
switch (ch)
{
case '+': f = a + b; printf("f = %d\n", f); break;
case '−': f = a - b; printf("f = %d\n", f); break;
case '*': f = a * b; printf("f = %d\n", f); break;
case '/': f = a / b; printf("f = %d\n", f); break;
default: printf("invalid operator\n");
}
}
}
如果我输入一个运算符,它会循环两次。第二次是空输入。
Let's say you typed a
followed by Enter.
第一次致电getchar()
回报a
但换行符仍然保留在输入流中。下一个呼叫getchar()
返回换行符而不等待您的输入。
有很多方法可以解决这个问题。最简单的方法之一是在调用后忽略该行的其余部分getchar()
.
ch = getchar();
// Ignore the rest of the line.
int ignoreChar;
while ( (ignoreChar = getchar()) != '\n' && ignoreChar != EOF );
您可以将其包装在一个函数中。
void ignoreLine(FILE* in)
{
int ch;
while ( (ch = fgetc(in)) != '\n' && ch != EOF );
}
and use
ch = getchar();
// Ignore the rest of the line.
ignoreLine(stdin);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)