2011-05-09 34 views
1

我的代碼應該閱讀來自用戶的線,如果符合「輸出」開始於然後它打印出「線路輸出」,並等待用戶輸入另一行。幫助scanf函數表現不同大端系統

如果行以「輸入」開頭,則輸出「行輸入」並終止。

我的代碼工作正常,英特爾的PC上,但是在Debian的SPARC看來scanf函數後的第一次犯規等待輸入,只是一個空行或某事無限讀取。

我要去哪裏錯了嗎?

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

int main() 
{ 
char buf[9000]; 
char key[5]; 
char *p=buf; 

int readMore=1; 

while(readMore) 
{ 
    //read in one line from stdin into buffer 
    scanf("%[^\n]",buf); 
    fflush(stdin); 

    sscanf(p, "%s",key); //get key from buffer 
    printf("Key:%s\n",key); //print key 

    if (strcmp("output",key)==0) 
    { 
     printf("Line is output\n"); 

    } 
    if (strcmp("input",key)==0) 
    { 
     readMore=0; 
     printf("Line is input\n"); 

     fflush(stdin); 
     getchar(); 
     return 0; 
    } 
    key[0]=0; 
    buf[0]=0; 
} //end while 

return 0; 
} 

固定這樣的:

...... 
int bytes_read; 
int nbytes = 100; 

while(readMore) 
{ 

     /* These 2 lines are the heart of the program. */ 
     p = (char *) malloc (nbytes + 1); 
     bytes_read = getline (&p, &nbytes, stdin); 
.... 

回答

4

這不是一個尾數問題。這是關於如何在不同平臺上執行標準輸入的緩衝。基本上,你不能在標準輸入(或其他任何輸入流)使用fflush() - C標準說這樣做是不確定的。

+0

那麼,如何進行呢? – mbwasi 2011-05-09 13:46:46

+0

@roman我真的不清楚爲什麼你認爲你需要衝洗流。只是刪除調用fflush – 2011-05-09 13:53:14

+0

刪除了電話,但沒有幫助,我想在stdin上不換行停留?我認爲我通過使用getline而不是scanf來修復它,儘管Thanx。 – mbwasi 2011-05-09 14:10:08