C语言 将大整数 txt 文件读取到 2D 数组中



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

#include <stdio.h>
#include <stdlib.h>
//max number of characters to read in a line. //MAXN=5 means 4 chars are read, then a  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; 
}

计数不会告诉你有多少个数字。进一步: 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("%dn", numbers[t]);
return 0;
}

输出:

10
20
30
40

最新更新