gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:41 25 4
gpt4 key购买 nike

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

(#)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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com