c - 将多行扫描到 C 中的结构数组中

标签 c arrays struct scanf

我正在寻找可以在以下格式的文本文件上实现的代码:

(#)string
int int int

例如:

#wisconsin
20 45 00
#zelda
13 45 20

我如何将其扫描到具有以下结构的数组中:

typedef struct{
    char string[99];
    int  first_int;
    int  second_int;
    int  third_int;
} input_t;

我目前的想法是:

input_t mydata[MAX_NAMES];
int count = 0;
while(mydata[count] = scanf("%s %d %d %d", input_t.string, 
    input_t.first_int, input_t.second_int, input_t.third_int,)){
        count++;
}

但这是行不通的,我不确定如何使用散列来识别一段数据的开始,而不是将它实际包含在字符串中。

最佳答案

这就是我大致要做的:

#include <stdio.h>

typedef struct{
    char string[99];
    int  first_int;
    int  second_int;
    int  third_int;
} input_t;

enum { MAX_NAMES = 20 };

int main(void)
{
    input_t mydata[MAX_NAMES];
    int i;
    for (i = 0; i < MAX_NAMES; i++)
    {
        if (scanf(" #%s %d %d %d", mydata[i].string, &mydata[i].first_int,
                  &mydata[i].second_int, &mydata[i].third_int) != 4)
            break;
    }
    int count = i;

    for (i = 0; i <  count; i++)
        printf("%s (%d, %d, %d)\n", mydata[i].string, mydata[i].first_int,
                  mydata[i].second_int, mydata[i].third_int);
    return 0;
}

对于输入文件:

#wisconsin
20 45 00
#zelda
13 45 20

显示的代码产生输出:

wisconsin (20, 45, 0)
zelda (13, 45, 20)

格式字符串中的前导空格是跳过读取三个整数后留下的换行符所必需的。

关于c - 将多行扫描到 C 中的结构数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43971151/

相关文章:

c - 我需要根据文件上有多少元素使用 X 结构,可以吗?

json - 在 BigQuery 中存储 JSON

c - 如何创建没有 MSVCR90D.dll 的 Win32 DLL?

c - 使用 fread() 时出现段错误

C - 链表 - 以相反的方式链接

C++ 指针数组为每个元素返回相同的值

JavaScript 过滤器返回 true 但不过滤

java - 将数组添加到 List<String[]> 时出错

c - "if an int can hold all values of the original type then the value is converted to int , else to unsigned int"——什么意思?

复杂的指针声明