tôi đã viết chương trình đơn giản này cho thực hành:Tại sao câu lệnh này được in hai lần trong vòng lặp?
#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;
}
Khi tôi chạy này, lần đầu tiên tôi được yêu cầu nhập vào một sự lựa chọn. Nếu tôi nhập 'E' hoặc 'R', nó đi vào khối 'trường hợp' tương ứng nhưng trong lần lặp tiếp theo trong vòng lặp while, nó không chờ tôi nhập vào lựa chọn của tôi. Thay vào đó, nó giả định tôi đã nhập "NULL" và yêu cầu lần thứ ba nhắc của tôi. Điều này liên tục xảy ra mỗi khi tôi nhập một lựa chọn. Đây là đầu ra của chương trình này. Tôi đang thiếu gì ở đây?
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$
Vì bạn nhấn e, sau đó nhấn enter. Đó là hai nhân vật. – immibis
'k = toupper (getchar());' -> 'k = toupper (getchar()); getchar();' một cho dòng mới. – BLUEPIXY