我正在尝试使用int age,int兄弟姐妹和char[]
hometown这三个变量构建结构,但是在运行程序时不允许我插入hometown字符串。整数可以正常工作,但是它会直接跳过数组并将其留空。我试过使用gets和fgets
,但似乎没有任何效果。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct person{
int age;
int s;
char hometown[20];
}p;
printf("Age: ");
scanf("%d",&p.age);
printf("Siblings: ");
scanf("%d",&p.s);
printf("Hometown: \n");
fgets(p.hometown, 20, stdin);
printf("Age \t Siblings \t Hometown\n");
printf("%d \t %d \t %s\n",p.age,p.s,p.hometown);
}
最佳答案
局部变量可能已经包含垃圾。
在使用字符串之前先尝试记忆,
这样适当的null将被终止。
尝试通过以下扫描获取您的输入(%s,p.hometown);
对于字符串,不需要&来收集字符串。
如果您仍然遇到问题,请告诉我。
关于c - 尝试构建结构,不要让我输入字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45704467/