c - 如何使用结构体

标签 c arrays struct

我试图打印这个结构,但我不知道出了什么问题。 该代码应该执行以下操作: -从键盘读取名字、姓氏、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/

相关文章:

arrays - 将字符串拆分为数组的最佳方法

javascript - 无法将数据插入数组

go - 包装结构引用

python - 包含复杂类型的 SWIG-ed C 结构的引用计数似乎没有按预期工作

C - 特定天数是多少小时?

c - 由于带有字符的输入函数 (scanf()) 存在一些问题,while 循环中的条件表达式出现奇怪的行为

c - USB 音频缓冲区溢出

php - MySQL 查询连接未完全检索

c - 错误 : unknown type name 'record'

c - 当我调用 C 代码时 R 卡住