2017-09-01 110 views
-1

我已經寫了一個讀命令函數。它將字符存儲到數組「前」(在一個新行開始)之前,並返回字符數,但似乎第一個單詞總是沒有被檢測到,並且有時在沒有識別單詞「去」的情況下它返回。誰能幫我。不勝感激!使用while循環讀取命令功能

int read_command(char *input){ 
    char inputarr[1000]; 
    int count=0; 

    do 
    { 
     inputarr[count++]=getchar(); 
     input++; 
    }while(inputarr[count-2]!='\n'&&inputarr[count-1]!='g'&& inputarr[count]!='o'); 

    inputarr[count--]='\0'; 
    inputarr[count--]='\0'; 

    for (int i=0 ;inputarr[i]!='\0';i++) { 
     printf("%c",inputarr[i]); 
    } 

    return count; 
} 

典型輸出:

1.

I like apple and how about you 
go 

like apple and how about you 
29Program ended with exit code: 0 

2.

I like today's weather 
and it is very sunny 

like today's weather 
22Program ended with exit code: 0 

謝謝!

+1

請給我們一個[MCVE]和正確地格式化代碼。至少顯示如何調用'read_command'和相關變量的聲明。 –

+4

兩件事:['getchar'](http://en.cppreference.com/w/c/io/getchar)函數返回一個'int'。你不檢查'EOF'。而這兩件事是相關的,['getchar'](http://en.cppreference.com/w/c/io/getchar)返回一個'int'只是爲了與'EOF'工作進行比較。 –

+3

您的while循環在第一次迭代中取消了一個負數作爲inputarr的索引。 – BurnsBA

回答

1

您尚未正確處理所有情況 - 1.如果「go」本身位於第一行,該怎麼辦? 2.如果以「go」子串開頭的句子中有第一個單詞怎麼辦? 3.在開始時,您無法檢查inputarr [count-2],因爲它將爲負值。 您可以參考在下面的程序,如果你輸入「走出去」並回車,然後它會打印所有的線 -

#include <stdio.h> 
int main(void) 
{ int c='\0'; 
    char ch[100]; 
    int i=0; 
    while (c != EOF){ 
     c = getchar(); 
     ch[i]=c; 
     i++; 
     printf("<%c>\n",c); 
     if(i >= 3 && ch[i-1] == 'o' && ch[i-2] == 'g' && ch[i-3] == '\n'){ 
      int j; 
      for(j=0;j<i-2;j++){ 
       printf("%c",ch[j]); 
      } 
      break; 
     } 
    } 
    return 0; 
}