我编写了一个读取命令函数。它将字符存储到单词“go”(新行开始)之前的数组中,并返回字符数,但似乎始终未检测到第一个单词并且有时它返回时没有识别出“go”一词。谁能帮我。非常感谢!
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. 如果“go”本身就在第一行怎么办? 2. 如果句子中第一个单词以“go”子串开头怎么办? 3. 一开始,您无法检查 inputarr[count-2],因为它将是负值。 您可以引用以下程序,其中如果您键入“go”并按 Enter 键,它将打印所有行-
#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;
}
关于c - 带 while 循环的读取命令函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001499/