新的這裏,我有一個非常簡單的問題。我在C中做了一個簡單的程序,它要求用戶輸入一個字符選擇。他們輸入結果後,程序返回到菜單。然而,它似乎需要某種類型的幽靈輸入,就好像該字符有一些未知的值。我需要將char設置回其默認狀態。C - 用戶單個字符輸入呈現奇怪的結果
代碼:
/* 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;
}
當'c'被選擇時你會做什麼? – Xymostech
@Xymostech當選擇c時,它會調用另一個函數來創建數據庫條目。我爲每個字段使用一個結構數組。這很好,但當回到menu()函數時,它將某些東西當作答案並呈現「無效的選擇」。如你看到的。 –
它看起來像其他功能沒有正確輸入輸入,所以有多餘的輸入留在緩衝區中,當你回到菜單時,已經選擇了一些東西。我們可以看到你所說的功能的代碼嗎? – Xymostech