Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c - Reading in Large Integer txt file into 2D array

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  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 
");
        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("
%d", numbers[i][j]);
       }
    }   
    fclose(inFile);
    return 0; 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

So this

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

should be something like:

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

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
", numbers[t]);
    return 0;
}

Output:

10
20
30
40

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...