-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
謝謝!
請給我們一個[MCVE]和正確地格式化代碼。至少顯示如何調用'read_command'和相關變量的聲明。 –
兩件事:['getchar'](http://en.cppreference.com/w/c/io/getchar)函數返回一個'int'。你不檢查'EOF'。而這兩件事是相關的,['getchar'](http://en.cppreference.com/w/c/io/getchar)返回一個'int'只是爲了與'EOF'工作進行比較。 –
您的while循環在第一次迭代中取消了一個負數作爲inputarr的索引。 – BurnsBA