Text file with different data types into structure array [closed]

筅森魡賤 提交于 2019-12-02 18:34:59

问题


I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:

A B 45.78965
A C 35.46731
B C 46.78695

The program that I'm reading it with is the following and it does not work. What am I doing wrong?

#include <stdio.h>

struct gra {
    char from;
    char to;
    double w;
};

int main ()
{
    FILE *fp = fopen("graph.txt", "r"); 
    int i = 0;
    while (!feof(fp)) {
        fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
        i++;
    }
    fclose(fp);
 }

回答1:


One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).

Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:

fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);

If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:

fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);

that is, use an extra space in the format before each "%c" to explicitly skip white space.

Your code has also a couple of other problems:

  1. You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.

  2. You are missing a definition of array graph.

I'm adding the complete code that I'd write for doing the parsing:

#include"stdio.h"
#define MAX 100

struct {
  char from, to;
  double w;
} graph[MAX];

int main ()
{
  FILE *fp = fopen("graph.txt", "rt");  
  for (int i=0; i<MAX; i++)
    if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
      break;
  fclose(fp);
  return 0;
}


来源:https://stackoverflow.com/questions/19152073/text-file-with-different-data-types-into-structure-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!