我正在完成我的任务,这是我遇到的问题。在赋值中,它表示中间初始值的输入值应为 - “L。A.”。但是,一旦我运行我的程序,它会在同一行上打印一些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
格式说明符读取由空格终止的字符序列。当你输入L. A.
时,只有L.
被读入middleInitial
,因为它停止在空间读取并且A.
被留在输入缓冲区中。在下一个scanf
上,它会立即读取那些缓冲的字符,因此它不会停止提示任何内容。
处理这个的最简单方法是在输入时省略空间,即L.A.
。如果你想支持空格,你将完全摆脱scanf
并使用fgets
一次读取所有内容。请注意,fgets
也会读取尾随换行符,因此您需要将其删除。