How to read data from a text file

2019-05-26 13:56发布

问题:

How do I read input from my text file? The input file is several lines long, and each line is of the format city city distance where there are two cities and the distance between them.

I have tried several things to read the input, but unfortunately those did not work. I need to parse the individual values on each line. (Each line consists of 2 city names and the distance between them.) Any help would be appreciated.

data = fopen(argv[1],"r");
while(!EOF){

while(1){
    c=fgetc(data);
    inname=(char**)malloc(sizeof(char*));
    if(c==' ')
        mode++;
    else    if(c=='\n'){mode=0;
        break;}
    else {
        switch(mode%3){
            case 0;
                for(i=0;fgetc(data)!=' ';i++){  
                    if(inname[count]!=NULL) {count++;inname=(char**)malloc(sizeof(char*));}
                    inname[count][i]=fgetc(data);}
                break;
            case 1; 
                if(inname[count]!=NULL){ count++;inname=(char**)malloc(sizeof(char*));}
                for(i=0;fgetc(data)!=' ';i++){  
                    inname[count][i]=fgetc(data);}
                break;                                      
            /*case 2;for(i=0;fgetc(data)!='\n';i++){    
                    dist[say]=atoi(str);}}}*/
                }}}count++;}
                `

回答1:

I think you should look into fscanf for reading formatted input like this.

To read a line containing two strings and an int, you would have something like:

fscanf(data, "%s %s %d", &city1, &city2, &distance);

To read multiple lines until EOF, your code should be of the following form:

while(fscanf(data, "%s %s %d", &city1, &city2, &distance)!=EOF) {
  /* rest of your logic here */
}