问题描述
试图创建一个程序来处理大型文本文件,并将其填充到行+列中。最终,我将不得不走计算机的最佳之路,但是在实现一个可以存储值的数组时遇到麻烦。
Attempting to create a program that reasons in a large Text File and filled them into Rows + Columns. Eventually I'll have to computer best path but having trouble just implementing an Array that can store the values.
#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;
}
推荐答案
计数不会告诉您如何有很多数字。另外:sscanf(line,%d,& numbers [i] [j]);
count does not tell you how many numbers there are. Further: sscanf(line, "%d", &numbers[i][j]); will just scan the same number every time.
因此,这
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
可以帮助您在扫描数字后移动到字符串的新位置。
where x
together with %n
helps you move to a new position in the string when a number has been scanned.
这里是扫描字符串中数字的简化版本:
Here is a simplified version that scans for numbers in a string:
#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
这篇关于将Large Integer txt文件读入2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!