在编写C程序时,我编写了以下代码,以便每个字符串可以输入多个单词
'
#include<stdio.h>
struct address
{
char house[20],street[20],city[10];
};
struct student
{
struct address A;
};
struct student getdata();
struct student getdata()
{
struct student s;
printf("\n\nEnter the Data\n\n");
printf("House : ");
if(fgets(s.A.house,20,stdin));
printf("Street : ");
if(fgets(s.A.street,20,stdin));
printf("City : ");
if(fgets(s.A.city,10,stdin));
return s;
}
int main()
{
struct student s;
int i;
printf("\nEnter the number\n");
scanf("%d",&i);
s=getdata();
}
但是在航站楼我得到了
House : Street :
那就是我无法为House提供数据,而是直接将我带到了Street。
最佳答案
调用scanf
之后,输入缓冲区中将剩下一个换行符。以后调用fgets
时,它将读取缓冲的换行符并立即返回。
要清除scanf
之后的输入缓冲区,请调用getchar
读取字符,直到读取换行符为止。
scanf("%d",&i);
while (getchar() != '\n');
s=getdata();
关于c - 在c字符串中输入多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45756948/