无法读取C中的结构数组

标签 c arrays structure

我正在尝试读取一个对象的成员,如下面的代码所示。 问题是代码无法读取数组中的第二个成员 (car[i].model) 和第三个成员 (car[i].price),只能读取第一个成员 (car[i].manufacturer)。

#include <stdio.h>
#include <conio.h>

struct machine
{
    int price;
    char manufacturer[30];
    char model[30];
};


int main()
{
    int i = 0, n;
    printf("Introduce number of cars: ");
    scanf_s("%d", &n);

    struct machine car[100];

    for (i = 0; i < n; i++)
    {
        printf("Data of the car nr. %d:\n", i+1);
        printf("Manufacturer: ");
        scanf_s("%s", car[i].manufacturer);
        printf("Model: ");
        scanf_s("%s", car[i].model); printf("\n");
        printf("Price: ");
        scanf_s("%d", &car[i].price); printf("\n");
    }
    for (i = 0; i < n; i++)
    {
        printf("Data of the car nr. %d:\n", i + 1);
        printf("Manufacturer: %s\n", car[i].manufacturer);
        printf("Manufacturer: %s\n", car[i].manufacturer);
        printf("Model: %s\n", car[i].model);
        printf("Price %d\n", car[i].price);
    }


    _getch();
}

最佳答案

scanf_s 要求为格式为 %s 的输入参数指定缓冲区大小。缓冲区大小包括终止空值。像这样调整您的代码:

struct machine
{
    int price;
    char manufacturer[30];
    char model[30];
};

struct machine car[100];
....
scanf_s("%s", car[i].manufacturer, 30 );
                                // ^^ buffer size
....    
scanf_s("%s", car[i].model, 30 );
                        //  ^^ buffer size
....
scanf_s("%d", &car[i].price);  // no buffer size

关于无法读取C中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34931060/

相关文章:

c - 使用 Structure 的数组进行排序

在汇编中从 32 位值转换为 8 位值,反之亦然,给出段错误

c - 在 C 中启动并初始化新的 char 数组后变量发生更改

c++ - 使用结构元素获取结构数组

c - 指向指针的指针数组删除错误

c++ - 有效地从文本文件中读取带有字符串索引的巨大二维数组(矩阵)

c - char 数据类型中的撇号

c - 将串行输入读取到 C 变量

具有灵活数组成员的 Python ctypes 结构到 bytearray

java - 如何将整数数组更改为字符串数组?