简体   繁体   中英

How to read data from a text file

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++;}
                `

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 */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM