简体   繁体   English

如何从文本文件读取数据

[英]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. 输入文件的长度为几行,每行的格式为city city distance ,其中有两个城市及其之间的距离。

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. (每行包括2个城市名称以及它们之间的距离。)任何帮助将不胜感激。

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. 我认为您应该研究fscanf以读取这样的格式化输入。

To read a line containing two strings and an int, you would have something like: 要读取包含两个字符串和一个int的行,您将具有以下内容:

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

To read multiple lines until EOF, your code should be of the following form: 要在EOF之前读取多行,您的代码应采用以下形式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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