新来的,我有一个非常简单的问题。我正在用 C 语言编写一个简单的程序,该程序要求用户输入如何处理字符的选项。在他们输入结果后,程序返回菜单。然而,它似乎需要某种幽灵输入,就好像 char 有一些未知值一样。我需要将 char 设置回其默认状态。
代码:
/* display menu for user */
void menu() {
printf("\n- - - Phone Book Database - - -\n");
printf("\nSelect an action:\n\n");
printf("\tc:\tCreate a database entry.\n");
printf("\ts:\tSearch the database entries.\n");
printf("\td:\tDelete a database entry.\n");
printf("\tq:\tQuit program.\n\n");
printf("Enter choice: ");
menu_choice = getchar();
if(menu_choice != 'c' && menu_choice != 's'
&& menu_choice != 'd' && menu_choice != 'q') {
printf("\n\n\tInvalid choice.\n");
menu();
}
//fflush(stdin);
}
这是一个示例输出:
- - - Phone Book Database - - -
Select an action:
c: Create a database entry.
s: Search the database entries.
d: Delete a database entry.
q: Quit program.
Enter choice: c
Enter name: test
Enter address: test
Enter number: 3
- - - Phone Book Database - - -
Select an action:
c: Create a database entry.
s: Search the database entries.
d: Delete a database entry.
q: Quit program.
Enter choice:
Invalid choice.
- - - Phone Book Database - - -
Select an action:
c: Create a database entry.
s: Search the database entries.
d: Delete a database entry.
q: Quit program.
Enter choice: q
输入 c 作为输入调用以下函数
/* creates a new record in array */
void create_record() {
char name[MAX];
char address[MAX];
int number;
rec_num++; /* add 1 to marker for record placement */
printf("\nEnter name: ");
scanf("%s", name);
printf("\nEnter address: ");
scanf("%s", address);
printf("\nEnter number: ");
scanf("%d", &number);
strcpy(record[rec_num].name, name);
strcpy(record[rec_num].address, address);
record[rec_num].number = number;
}