getchar在交换机情况下不工作(c)

使用一个非常简单的计算器程序,提示用户执行操作,然后提示两个整数来执行此操作。 程序应该在这些操作之后循环,除非用户输入字符’q’,此时程序应该退出。

#include  int main (void) { char c; int number[2], num1, num2, result; double num1d, num2d, resultd; int done=1; while(done) { printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n"); c = getchar(); printf("\tplease enter a number \n"); scanf("%d",&number[0]); printf("\tplease enter another number \n"); scanf("%d",&number[1]); num1 = number[0]; num2 = number[1]; switch(c) { case('-'): result = num1-num2; printf("\nThe first number you entered subtracted by the second number is %d.\n", result); break; case('+'): result = num1+num2; printf("The first number you entered added to the second number is %d.\n", result); break; case('*'): result = num1*num2; printf("The first number you entered multiplied with the second number is %d.\n", result); break; case('/'): num1d = (double) num1; num2d = (double) num2; resultd = num1d/num2d; printf("The first number you entered divided by the second number is %g.\n", resultd);; break; case('q'): printf(" Now Exiting...\n"); done=0; break; default: puts("Invalid key pressed. Press q to exit"); break; } } return 0; } 

对于单次计算可以正常工作,但随后执行奇怪; 特别是它打印

 printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n"); printf("\tplease enter a number \n"); 

共。

清除输入缓冲区的标准方法while (getchar() != '\n'); 不解决这个问题。 该文本显示不正确的两次中的一次仍然可以使用该程序,就像指令正在显示一样(因此用户可以键入操作,如+,回车,然后是一些整数和回车,程序将从那一点开始正确执行)每隔一次,程序将按“无效键按下。无论输入如何,按q退出”。

这里的每个人都说的是真的, getchar()返回一个int但这不是你的问题。

问题是getchar()在使用后会留下换行符。 如果您要使用getchar() ,则必须始终使用换行符。 这个简单的修复:

  printf("\t What sort of operation would you like to perform? \n \t Type + - * / accordingly. \n"); c = getchar(); getchar(); //<-- here we do an extra getchar for the \n printf("\tplease enter a number \n"); scanf("%d",&number[0]); printf("\tplease enter another number \n"); scanf("%d",&number[1]); 

这将消除这个问题。 每次你输入它确实在缓冲区上放了两个字符,例如,如果我点击+并输入我得到:

 '+''\n' // [+][\n] 

getchar()只会得到第一个,然后当再次调用getchar()时它不会等待你的输入它只需要'\n'然后转到scanf()

您不应该逐个字符地混合使用更高级别的输入函数,例如scanf() 。 最好使用scanf()输入命令字符,但当然你必须在命令后按Enter键。 我相信这是你问题的根本原因。

getchar()getchar() ,请注意getchar() ,尽管它的名称,返回int而不是 char 。 这是因为它可以返回EOF ,这是一个特殊常量,其值与所有字符的值不同。

此外,您应该始终检查I / O函数的返回值,如scanf() ,如果输入与模式字符串不匹配,它们可能会失败。

作为调试提示,您当然可以在解释之前打印c的值,这样您就可以更轻松地查看和理解程序的流程。

我猜这是第一次有效,但不是下一次。 这是因为scanf调用将换行符留在输入缓冲区中,因此下次在循环中调用getchar时它将返回换行符。 在scanf调用中的格式之后添加空格

 scanf("%d ",&number[0]); 

它将从缓冲区中丢弃剩余的空格。

使用调试器逐步执行代码并检查变量以进行validation。

你的getchar应该返回int 。 原因如下

 getchar reads characters from the program's standard input and returns an int value suitable for storing into a char. The int value is for one reason only: not only does getchar return all possible character values, but it also returns an extra value to indicate that end-of-input has been seen. The range of a char might not be enough to hold this extra value, so the int has to be used. 

所以基本上你需要在代码中将char c更改为int c