-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