【问题标题】:How to read data from a text file如何从文本文件中读取数据
【发布时间】:2012-06-10 18:36:34
【问题描述】:

如何从我的文本文件中读取输入?输入文件有几行,每行格式为city city distance,其中有两个城市以及它们之间的距离。

我已经尝试了几种方法来读取输入,但不幸的是这些方法都不起作用。我需要 解析每一行上的各个值。 (每行包含 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++;}
                `

【问题讨论】:

    标签: c file file-io input


    【解决方案1】:

    我认为您应该查看fscanf 以读取这样的格式化输入。

    要读取包含两个字符串和一个 int 的行,您会得到如下内容:

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

    要读取多行直到 EOF,您的代码应采用以下形式:

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

    【讨论】:

    • U 的意思是,如果我这样写的话 `while(!EOF){ while(1){fscanf(data,"%s %s %d", &city1[i], &city2[i ], distance[i]);} i++;} 当然如果它们都是双指针
    • @MAK: fscanf 返回读取的 items 数,而不是字节数。此外,最好为%s 转换说明符指定最大字段宽度。
    • 我无法升级答案,因为我没有足够的声誉
    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2015-12-10
    相关资源
    最近更新 更多