gpt4 book ai didi

c - 将大整数txt文件读入二维数组

转载 作者:行者123 更新时间:2023-11-30 21:05:50 24 4
gpt4 key购买 nike

尝试创建一个程序,在大型文本文件中进行推理并将其填充到行+列中。最终我将不得不计算最佳路径,但在实现可以存储值的数组时遇到麻烦。

#include <stdio.h>
#include <stdlib.h>

//max number of characters to read in a line. //MAXN=5 means 4 chars are read, then a \0 added in fgets. See reference for functionality

#define MAXN 100L
int main(void) //char** argv also ok {
int i=0, totalNums, totalNum,j=0;
size_t count;
int numbers[100][100];
char *line = malloc(100);
FILE* inFile ;
inFile = fopen("Downloads/readTopoData/topo983by450.txt", "r"); //open a file from user for reading

if( inFile == NULL) { // should print out a reasonable message of failure here
printf("no bueno \n");
exit(1);
}

while(getline(&line,&count, inFile)!=-1) {
for(;count>0; count--,j++)
sscanf(line, "%d", &numbers[i][j]);
i++;
}

totalNums = i;
totalNum = j;
for(i=0;i<totalNums; i++){
for(j=0;j<totalNum;j++){
printf("\n%d", numbers[i][j]);
}
}
fclose(inFile);
return 0;
}

最佳答案

count 并不能告诉你有多少个数字。进一步: sscanf(line, "%d", &numbers[i][j]);每次都会扫描相同的号码。

所以这个

    for(;count>0; count--,j++)
sscanf(line, "%d", &numbers[i][j]);

应该是这样的:

    j = 0;
int x = 0;
int t;
while(sscanf(line + x, "%d%n", &numbers[i][j], &t) == 1)
{
x += t;
++j;
}

其中 x%n 一起帮助您在扫描数字后移动到字符串中的新位置。

这是一个扫描字符串中数字的简化版本:

#include <stdio.h>

int main(void) {
char line[] = "10 20 30 40";
int numbers[4];
int j = 0;
int x = 0;
int t;
while(j < 4 && sscanf(line + x, "%d%n", &numbers[j], &t) == 1)
{
x += t;
++j;
}
for(t=0; t<j; ++t) printf("%d\n", numbers[t]);
return 0;
}

输出:

10
20
30
40

关于c - 将大整数txt文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52463812/

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