首页 > 解决方案 > 从c中的文件中读取文本并忽略“一些评论”

问题描述

我目前正在制作一个程序来读取这个文本文件(从意大利语翻译)并将一行存储在一个单链表中。但我不得不忽略评论。注释以“#”开头。在我的列表节点中,我必须有成分、符号和数量,没有注释。

Input file:

#ingredients for donut
milk    l   0.25
flour   g   300
oil     l   0.05 # a spoon
eggs    u   2
butter  g   50
yogurt  g   50 # white yogurt
# enjoy your meal



struct nodo {
  char ingredient[15];
  char simbol[2];
  float quantity;
  struct nodo * next;
};

我尝试了一些代码,现在我被困在这个(读取功能):

struct nodo * read (struct nodo * top) {
FILE *fp;
fp = fopen("ingredients.txt", "r");

char comment[30];
char comm;

while(!feof(fp)) {
    
    fscanf(fp, "%c", &comm);
    
    if(comm == '#') {
        fgets(comment, 30, fp);
    }
        
    struct nodo * new = CreaNodo();
    fscanf(fp, "%s%s%f", new->ingredient, new->simbol, &new->quantity);
        
  if(!top) top = new;
  else {
        new->next = top;
        top = new;
     }
  }

fclose(fp);
return top;
}

标签: clisttext

解决方案


第二个 fscanf 没有非注释行的第一个字符(它在 comm 变量中丢失)。

fgets()'ing 每一行,然后在该行中搜索'#',如果没有找到,则 sscanf()'ing 行更容易(我的观点)并且可能更有 I/O 效率。


推荐阅读