我試圖在C中創建一個小型地址簿程序,用戶可以輸入存儲在文本文件中的聯繫信息。如果用戶選擇添加新聯繫人,程序應該詢問他們是否在完成後添加另一個聯繫人。我做了一個if語句,如果他們輸入'n',或者如果他們另外寫入其他聯繫人,則認爲應該結束循環。但是,如果用戶鍵入'y'(或其他任何東西),它總是在1循環後退出。雖然while循環始終在第一個循環後退出
void new_contact(void){
printf("Ready for new contact\n");
int enter_new_contact = 1;
char first_name[15];
char second_name[20];
char phone_number[12];
char email[50];
char y_n[1];
do{
printf("Enter the contacts first name.\n");
scanf("%s", first_name);
printf("Enter the contacts second name.\n");
scanf("%s", second_name);
printf("Enter the contacts phone number.\n");
scanf("%s", phone_number);
printf("Enter the contacts email.\n");
scanf("%s", email);
printf("%s\t%s\t%s\t%s\n", first_name, second_name, phone_number, email);
printf("Would you like to add another contact?\n");
scanf("%s", y_n);
printf("%s\n", y_n);
if(strcmp(y_n, "n")==0){
enter_new_contact=0;
}
}while(enter_new_contact==1);
}
在此先感謝!
第一件事:解決不確定的行爲,如'焦炭y_n [1];'是不是大到足以容納一個字符,一個空終止符。 –
'char y_n [1];':這個字符緩衝區太小了。它不能容納任何明顯的字符串。您需要空終止符的空間。當用戶輸入「是」或「否」時會發生什麼? –