将数据从txt文件导入C程序

时间:2018-03-29 18:40:23

标签: c file struct scanf

我正在尝试将数据从txt文件导入C程序。 txt文件格式如下:

George_Washington 1789-1797 Unaffiliated
John_Adams 1797-1801 Federalist
Thomas_Jefferson 1801-1809 Democratic_Republican
James_Madison 1809-1817 Democratic_Republican
James_Monroe 1817-1825 Democratic_Republican
John_Quincy_Adams 1825-1829 Democratic_Republican
Andrew_Jackson 1829-1837 Democrat
Martin_Van_Buren 1837-1841 Democrat
... (total 45 lines)

我有一个结构来保存我的变量

typedef struct
{
    char name[30];
    char date[10];
    char party[25];
}presidents;

我正在尝试将数据从txt移动到我的main函数中,进入单独的数组:name,date,party。

int main(void)
{
    FILE *file;
    int i = 0;
    presidents presidents_data[45];

    file = fopen("data.txt", "r");

    while (3 == fscanf(file, "%30s %10s %25s", &presidents_data[i].name,
    &presidents_data[i].date, &presidents_data[i].party))
    {
        printf("");
        i++;
    }

    for (i = 0; i < 45; i++)
    {
        printf("Name: %s, Years: %s, Party: %s\n", presidents_data[i].name,
        presidents_data[i].date, presidents_data[i].party);
    }
}

我在编译时收到错误消息说&#34;格式指定类型&#39; char **&#39;但是参数的类型为&#39; char(*)[30]&#39;&#34;

看起来这些变量并不匹配。

我对编码很陌生,所以感谢任何帮助!

0 个答案:

没有答案