我正在尝试创建一个包含三个变量 int age、int brothers 和 char[]
home 的结构,但它不允许我在程序运行时插入家乡字符串。整数工作正常,但它只会跳过数组并将其留空。我尝试过使用 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);
}
最佳答案
局部变量可能已经包含垃圾。
在使用字符串之前尝试 memset, 这样正确的 null 将被终止。
尝试通过以下 scan(%s, p.hometown) 获取您的输入;
对于字符串,不需要 & 来收集字符串。
如果您仍然遇到该问题,请告诉我。
关于c - 试图创建一个结构,不让我输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704467/