我试图打印这个结构,但我不知道出了什么问题。 该代码应该执行以下操作: -从键盘读取名字、姓氏、ss# 和年龄,并将它们保存在变量:person 中。
-显示变量:person 中的姓氏、名字、年龄和 ss#。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Rec
{
char firstName [20];
char lastName [30];
char ss [12];
int age;
};
int main()
{
struct Rec person;
char personInfo[100];
int i;
printf("Enter a first name, a space, a last name, a space, a ss#, a space, and an age all on the same line.");
scanf("%s" , &personInfo);
for (i=0, i<100; i++)
{
int count=0, z=0;
if (personInfo[i]= ' ')
count++;
else if( count ==0)
{
for (z=0; z<100; z++)
person[z].firstName=personInfo[i];
}
else if (count ==1)
{
for (z=0; z<100; z++)
person[z].lastName=personInfo[i];
}
else if (count ==2)
{
for (z=0; z<100; z++)
person[z].ss=personInfo[i];
}
else if (count ==3)
{
for (z=0; z<100; z++)
person[z].age=personInfo[i];
}
}
printf("Name: %s %s, Social Security: %s, Age: %d\n", person[i].firstName, person[i].lastName, personInfo[i].ss, personInfo[i].age);
system("Pause");
}
最佳答案
我发现的问题:
一个
scanf("%s" , &personInfo);
scanf
当发现空格时将停止读取。它只会读取名字。
您需要使用fgets
检索一行文本,包括空格。
两个
person[z].firstName=personInfo[i];
person[z].firstName
的类型为 char [20]
。 personInfo[i]
的类型为 char
。这是无效的分配。我不清楚你的意图。
三
printf("Name: %s %s, Social Security: %s, Age: %d\n", person[i].firstName, person[i].lastName, personInfo[i].ss, personInfo[i].age);
执行该行时,i
的值为100
。您正在访问 person[100]
,这超出了分配的有效内存。它将导致未定义的行为。
建议
如果要读取 100
条记录并逐条打印它们,则需要两个 for
block ,而不是一个。第一个 for
循环迭代人数。第二个 for
循环迭代读取的每行字符。
for (i=0, i<100; i++)
{
// Read the record of the i-th person.
fgets(personInfo, 100, stdin);
for ( int j = 0; j < 100; ++j )
{
// Extract the info from the line and fill up the data
// in person[i]
}
// Print the record of the i-th person.
}
关于c - 如何使用结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532272/