2011-04-13 50 views
1

我想输入txt文件到我的C程序,它看起来像这样如何在C中的每一行上的特定位置后忽略字符?

123 x 182 //this is a comment in the file 
1234 c 1923 //this is another comment in the file 
12 p 3  //this is another comment in the file 

我需要存储我想忽略一切的INT,单个字符和其他INT在每一行,然后在线上。这是我试过的....

while (fscanf(file, "%d %c %d", &one,&two,&three) !=EOF) 
       { 
         printf("%d %c %d\n", one,two,three); 
       } 

现在我只是打印出测试过程的值。所以,如果我测试这个文件,没有任何评论或额外的东西,我需要的前三件事情后,它完美的作品。但是如果有额外的东西,我会陷入一个无限循环,第一行被重复打印。

回答

0

在C中可能有更好的方法,但是您可以在当前循环中添加一个循环来读取其余字符,直到您遇到换行符为止。

while (fscanf(file, "%d %c %d", &one,&two,&three) !=EOF) 
{ 
    printf("%d %c %d\n", one,two,three); 
    while(fgetc(file) != '\n'){}; 
} 

这应该打出来的嵌套while循环,一旦它得到的字符是一个换行符,而接下来的fscanf将开始下一行。

+0

雅,实际上做的伎俩。谢谢 – Joel 2011-04-13 06:26:39

0

如果你的libc支持POSIX 2008(比如至少在Linux上glibc的一样),你可以使用函数getline和sscanf:

int len; 
char *line; 
while (getline(&line, &len, file) != -1) { 
    sscanf(line, "%d %c %d", &one, &two, &three); 
    printf("%d %c %d\n", one,two,three); 
    ... 
} 
相关问题