我写了这个简单的程序来练习:
当我运行这个程序时,它首先要求我输入一个选项。如果我输入'E'或'R',它会进入相应的'case'块,但在while循环的下一次迭代中,它不等待我输入我的选择。相反,它假定我输入了“NULL”,并第三次要求我的提示。每次我输入一个选项时,这种情况都会发生。以下是此程序的输出。我错过了什么?
我为练习编程写了这个简单的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CLASSES 3
#define STUDENTS 4
int grades[CLASSES][STUDENTS];
int main(void)
{
int i = 1;
char t,k;
while(i == 1)
{
printf("\n\n\nMENU:\nEnter the grades(E)\nReport Grades(R)\nQuit(Q)\nYour choice: ");
k = toupper(getchar());
printf("Input entered... %c\n", k);
switch(k) {
case 'E' :
printf("Entering the grades..\n");
break;
case 'R' :
printf("Reporting the grades...\n");
break;
case 'Q' :
printf("Quitting the program...\n");
exit(0);
break;
default:
printf("ERROR: %c: Incorrect menu option\n", k);
break;
}
}
return 0;
}
当我运行这个程序时,它首先要求我输入一个选项。如果我输入'E'或'R',它会进入相应的'case'块,但在while循环的下一次迭代中,它不等待我输入我的选择。相反,它假定我输入了“NULL”,并第三次要求我的提示。每次我输入一个选项时,这种情况都会发生。以下是此程序的输出。我错过了什么?
host-mb:c_practice host$ ./asd
MENU:
Enter the grades(E)
Report Grades(R)
Quit(Q)
Your choice: E
Input entered... E
Entering the grades..
MENU:
Enter the grades(E)
Report Grades(R)
Quit(Q)
Your choice: Input entered...
ERROR:
: Incorrect menu option
MENU:
Enter the grades(E)
Report Grades(R)
Quit(Q)
Your choice: R
Input entered... R
Reporting the grades...
MENU:
Enter the grades(E)
Report Grades(R)
Quit(Q)
Your choice: Input entered...
ERROR:
: Incorrect menu option
MENU:
Enter the grades(E)
Report Grades(R)
Quit(Q)
Your choice: Q
Input entered... Q
Quitting the program...
host-mb:c_practice host$
k = toupper(getchar());
-->k = toupper(getchar());getchar();
一个是为了读取新行。 - BLUEPIXY