我的代码存在问题,其中输出将比我希望的更早打印语句,并被告知这是由于输入缓冲,并且在scanf中的“%”之前添加空格可以解决问题,但仍然是经常发生的问题。
printf(“请输入联系人的名字:”);scanf(“%31s”,name.firstName);
printf("Do you want to enter a middle initial(s)? (y or n): ");
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
{
printf("Please enter the contact's middle initial(s): ");
scanf(" %7s", name.middleInitial);
}
printf("Please enter the contact's last name: ");
scanf(" %36s", name.lastName);
// Contact Address Input:
printf("Please enter the contact's street number: ");
scanf(" %d", &address.streetNumber);
printf("Please enter the contact's street name: ");
scanf(" %41s", address.street);
printf("Do you want to enter an apartment number? (y or n): ");
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
{
printf("Please enter the contact's apartment number: ");
scanf(" %d", &address.apartmentNumber);
}
printf("Please enter the contact's postal code: ");
scanf(" %8s", address.postalCode);
printf("Please enter the contact's city: ");
scanf(" %41s", address.city);
// Contact Numbers Input:
printf("Do you want to enter a cell phone number? (y or n): ");
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
{
printf("Please enter the contact's cell phone number: ");
scanf(" %11s", numbers.cell);
}
printf("Do you want to enter a home phone number? (y or n): ");
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
{
printf("Please enter the contact's home phone number: ");
scanf(" %11s", numbers.home);
}
printf("Do you want to enter a business phone number? (y or n): ");
scanf(" %c", &option);
if (option == 'y' || option == 'Y')
{
printf("Please enter the contact's business phone number: ");
scanf(" %11s", numbers.business);
}
您的代码的问题是,scanf
倾向于至少在stdin
缓冲区中保留换行符,至少取决于您的输入,因此下一次读取将读取这些未读取的字符并弄乱您的事件序列需要您的程序。对于单个字符," %c"
是一个很好的解决方案,但对您的"%ns"
输入而言可能不是那么有效。