[英]Scanf skips functions
我正在完成我的任務,這就是我遇到的問題。 在分配中,它說中間首字母的輸入值應該是這個 - “LA”。 但是,一旦我運行我的程序,它就會在同一行打印一些 printf 函數,跳過 scanf 函數。 我已經討論了很多關於“%c”問題的主題,但我仍然無法使我的程序正常運行。 一些變量來自 .h 文件。 實際任務更大,但它幾乎是重復的,所以我想如果我想出如何解決這個問題,我將能夠最終完成我的任務。
int main(void){
// Declare variables here:
char ch;
struct Name FullName = { {'\0'} };
struct Address AddressInfo = { 0, '\0', 0, '\0', '\0' };
struct Numbers PhoneInfo = { {'\0'} };
// Display the title
printf("Contact Management System\n");
printf("-------------------------\n");
// Contact Name Input:
printf("Please enter the contact’s first name: ");
scanf("%s", &FullName.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &ch);
if (ch == 'y') {
printf("Please enter the contact’s middle initial(s): ");
scanf(" %s", FullName.middleInitial);
}
printf("Please enter the contact’s last name: ");
scanf(" %s", &FullName.lastName);
// Contact Address Input:
printf("Please enter the contact’s street number: ");
scanf("%d", &AddressInfo.streetNumber);
輸出(我已突出顯示輸入值):
Contact Management System
-------------------------
Please enter the contactÆs first name: *Artem*
Do you want to enter a middle initial(s)? (y or n): *y*
Please enter the contactÆs middle initial(s): *L. A.*
Please enter the contactÆs last name: Please enter the contactÆs street number:
%s
格式說明符讀取以空格結尾的字符序列。 當您輸入LA
,只有L.
被讀入middleInitial
因為它在空間處停止讀取,而A.
留在輸入緩沖區中。 在下一個scanf
,它會立即讀取這些緩沖的字符,因此它不會停止提示任何內容。
處理這個最簡單的方法是在輸入時省略空格,即LA
。 如果您想支持空格,您將需要完全擺脫scanf
並使用fgets
一次完整地閱讀所有內容。 請注意, fgets
還會讀取結尾的換行符,因此您需要將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.