C 如何解决此输入缓冲问题?
我的代码有一个问题,输出将比我希望的更早地打印语句,我被告知这是由于输入缓冲,在scanf中的“%”之前添加一个空格可以解决这个问题,但这仍然是一个反复出现的问题 printf(“请输入联系人的名字:”); scanf(“%31s”,name.firstName)C 如何解决此输入缓冲问题?,c,string,scanf,user-input,C,String,Scanf,User Input,我的代码有一个问题,输出将比我希望的更早地打印语句,我被告知这是由于输入缓冲,在scanf中的“%”之前添加一个空格可以解决这个问题,但这仍然是一个反复出现的问题 printf(“请输入联系人的名字:”); scanf(“%31s”,name.firstName) 您的示例显示了要由scanf(“%41s”,address.street)扫描的输入是“基尔街”。但是%s格式说明符在第一个空格处停止,因此这不起作用。我建议scanf(“%41[^\n]”,address.street)。您只需要将
您的示例显示了要由
scanf(“%41s”,address.street)扫描的输入代码>是“基尔街”。但是%s
格式说明符在第一个空格处停止,因此这不起作用。我建议scanf(“%41[^\n]”,address.street)代码>。您只需要将前导空格放在前面,并且%c
,因为其他格式会自动过滤前导空格。类似地,对于可能不止一个单词的任何其他字符串,例如城市“纽约”和姓氏“Da Silva”等,您还应始终检查scanf
的返回值,即成功扫描的项目数。回到前面的评论,我认为清除输入缓冲区不是问题,而是一个字符串中有多个单词。我认为发布了错误的副本。问题不在于清除输入缓冲区(OP已采取步骤清除前导空格),而在于不读取多个字符串的整个输入。
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);
}