gpt4 book ai didi

c - 从文件中读取固定长度的整数行(bu

转载 作者:行者123 更新时间:2023-11-30 15:29:42 25 4
gpt4 key购买 nike

我正在尝试逐行读取文件(长度为 16),但行数未知,并将它们存储到整数数组中,然后添加到链接列表中。这就是我开始的地方,但我正在努力将其扩展为读取多行(因为我不知道会有多少行)。有没有比使用当前方法更好的方法来实现我想要的目标?

int deck[16];
while (fgetc(f) != EOF) {
for (int i = 0; i < DECK_SIZE; i++) {
c = fgetc(f);
tempNum = c - '0';
if(tempNum < MIN_CARD || tempNum > MAX_CARD) {
failed = 1;
}
deck[i] = (int)tempNum;
}

if(fgetc(f) != '\n') { // file too long
failed = 1;
}

//CREATE A NODE, ADD IT TO THE LINKED LIST
}


Example contents of a file (1): (each line holds 16 numbers)
1234567891234564
9876543211234233

Example contents of a file (2): (each line holds 16 numbers)
1234567891234562
9876543211234233
2354365457658674
3634645756858665

最佳答案

#include <stdio.h>

enum {
DECK_SIZE = 16
};

int main()
{
char deck[DECK_SIZE + 2];
while (fgets(deck, sizeof(deck), stdin)) {
char* ch;
for (ch = deck; *ch; ++ch) {
*ch -= '0';
}
if (ch - deck!= DECK_SIZE + 1) {
return 1;
}

// CREATE A NODE, ADD IT TO THE LINKED LIST
}

return 0;
}

关于c - 从文件中读取固定长度的整数行(bu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115910/

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