2012-08-13 140 views
1

我寫了一個C程序來分類一些字符串。我使用FILE流來讀取和寫入文件。但是我發現了一個問題。通常它應該對字符串進行分類,但事實並非如此。我認爲這個代碼是好的,所以我找不到問題。請幫幫我。這個C代碼有什麼問題?

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char line[80]; //create a string 
    FILE *r_in = fopen("spooky.csv", "r"); // this is the source file 
    FILE *w_ufo = fopen("ufo.txt", "w"); // strings with "UFO" will be written to here 
    FILE *w_disapp = fopen("disappearance.txt", "w"); // strings with "Disappearance" will be written to here 
    FILE *w_others = fopen("others.txt", "w"); // others will be written to here 

    while (fscanf(r_in, "%79[\n]\n", line) == 1) 
    { 
     if(strstr(line, "UFO")) // I think here is the problem (with strstr()) 
      fprintf(w_ufo, "%s\n", line); 
     else if(strstr(line, "Disappearance")) 
      fprintf(w_disapp, "%s\n", line); 
     else 
      fprintf(w_others, "%s\n", line); 
    } 

    fclose(w_ufo); 
    fclose(w_disapp); 
    fclose(w_others); 

    return 0; 
} 

源文件 「spooky.csv」:

30.685163,-68.137207,Type=Yeti 
28.304380,-74.575195,Type=UFO 
29.132971,-71.136475,Type=Ship 
28.343065,-62.753906,Type=Elvis 
27.868217,-68.005371,Type=Goatsucker 
30.496017,-73.333740,Type=Disappearance 
26.224447,-71.477051,Type=UFO 
29.401320,-66.027832,Type=Ship 
37.879536,-69.477539,Type=Elvis 
22.705256,-68.192139,Type=Elvis 
27.166695,-87.484131,Type=Elvis 

我認爲這個問題是的strstr(),請告訴這個問題。

+1

如果你想讀整行,你應該使用'fgets'來代替。 – 2012-08-13 11:46:11

回答

4

問題出在fscanf。您可能想要:

while (fscanf(r_in, "%79[^\n]\n", line) == 1) 
         ^

或者只是使用fgets作爲Joachim Pileborg評論。

while (fgets(line, sizeof(line), r_in)) 
+0

謝謝Bro! – 0xEDD1E 2012-08-13 12:01:54