2011-04-13 52 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); 
    ... 
} 
相關問題