2012-03-24 54 views
0

我想從./sample < input.txt命令中讀取文件,但它不會因EOF而停止。
我需要按Ctrl + C來確定它是EOF。
那麼我怎樣才能閱讀多行?
我需要把它放入主循環,它可以確定EOF沒有按Ctrl + C。 按照我的計劃,必須有2個循環: 主循環:從文件中獲取其他行,插入新節點以填充條件應該是「EOF」。 子循環:按字符填充字符數組,條件應爲「\ n」。鏈接列表文件輸入,不能用EOF停止

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

#define SIZE 80 


struct node { 
    char str[SIZE]; 
    struct node* next; 
}; 

void read_line(struct node* line_list); 

int main(void) 
{ 

    struct node* line_list = NULL; // linked list - headp 

    read_line(line_list); 

    return 0; 
} 

void read_line(struct node* line_list) 
{ 
    int ch, i = 0; 

    struct node* temp = malloc(sizeof(struct node)); 
    if(temp!=NULL) { 
     while((ch = getchar()) != EOF){ 
     if (ch != '\n') 
     { 
      temp->str[i] = '\0'; 
      //insert(&line_list,temp.str); 
      break; 
     } 
     if (i < SIZE) 
      temp->str[i++] = ch; 
     printf("New str: %s\n",temp->str); 
     } 
    } 
} 
+1

當你調試的代碼是什麼ch的值時,EOF達到? – Gangadhar 2012-03-24 05:07:57

+0

其實,我真的不知道如何調試:(我在cygwin上工作,如果你告訴我,我可以嘗試調試它 – user1289547 2012-03-24 05:21:15

+0

@ user1289547你確定輸入文件中的第一個字符不是換行符嗎?樣本輸入文件的內容。 – 2012-03-24 05:54:39

回答

1

編輯

忽略我原來的職位,我不是對上週五晚上思考。正如Peter指出的那樣,你的while循環測試有一個不同的問題。但是,您仍然需要在malloc之後檢查temp != NULL

+0

而(CH!= EOF){ \t而((CH =的getchar() !)= '\ n'){ \t \t如果(I STR [1 ++] = CH; \t} \t \t temp-> str [i] ='\ 0';我有一個問題是我需要一個主循環,當我寫他們都在相同的條件我只能生成1個字符串,我可能需要以完整的數組 – user1289547 2012-03-24 05:26:22

+0

@ user1289547我似乎無法理解「主循環」的含義。請編輯你的問題來解釋你的問題是什麼。在任何情況下,使用邏輯與來測試換行符和'EOF'都沒有意義。另外,你需要做:'if(temp!= NULL){... while ...}'。在解除引用temp之前,你需要確保'malloc'成功。 – 2012-03-24 05:31:42

+0

我編輯過。您可以通過「// insert(line_list)」來理解我想要做什麼。我想將行作爲字符並將它們存儲到鏈接列表中。我的代碼獲得第一行成功,但不停止W/O CTRL + C命令。 – user1289547 2012-03-24 05:40:20

2
while ((ch = getchar()) != EOF) { // now you have your valid ch 
    if (ch == '\n') break; // end-of-line is a quitter 
} 

EDITH說:abtract與concret。 好吧,我去退一萬步,寫你的代碼在僞

while ((ch = getchar()) != EOF) { 
    // this is a foreverloop until you hit end of file 

    // now comes the state machine 
    if (ch != NEWLINE) { 
    // collect the string 
    string.add(ch); // pseudocode 
    } else { 
    // do some accountings with the collected string 
    list.add(string); // pseudocode 
    string.print(); 
    } 
} 
+0

彼得正指着你走向正確的方向。 – 2012-03-24 05:45:53

+0

它現在甚至不讀取文件。因爲我在運行程序後看不到任何打印。 – user1289547 2012-03-24 05:50:18

+0

@ user1289547編輯您的問題以顯示您如何修改代碼。 – 2012-03-24 05:51:23