出于某种原因,一旦我输入要搜索的字符,主循环将终止,但目的是为了能够输入一行然后搜索一个字符你输入一个空行(不输入任何内容)。基本上我会想无限地做第1步和第2步,直到我输入任何内容并按回车。为什么这不起作用?感谢任何人的帮助!while循环没有按预期继续
此外,一个小问题,如何在输入字符进行搜索后清除任何垃圾?
#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
char array[SIZE],search;
int found[SIZE],i,charsFound;
//Step 1
printf("Enter a line of text(empty line to quit): ");
while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
//Step 2
printf("Enter a character to search: ");
search=getchar();
charsFound=CharIsAt(array,search,found,SIZE);
printf("Entered text: ");
fputs(array,stdout);
printf("Character being searched for: %c\n",search);
printf("Character found at %d location(s).\n",charsFound);
for (i=0;i<charsFound;i++)
printf("%c was found at %d\n",search,found[i]);
printf("Enter a line of text(empty line to quit): ");
}
return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
//Searches for ch in *pStr by incrementing a pointer to access
//and compare each character in *pStr to ch.
int i,x;
for (i=0,x=0;i<mLoc;i++){
if (*(pStr+i)==ch){
//Stores index of ch's location to loc
loc[x]=i;
x++; //Increment for each time ch was counted in pStr
}
}
//Returns the number of times ch was found
return x;
}
我包括我的整个代码,如果这不是太讨厌,我可以尝试,使问题的一个简化版本是否会有所帮助。我认为整个代码可能对回答这个问题更有用。
再次感谢,欢呼!
功能的顶部:'的getchar()'实际上返回一个'int'。因此,变量'search'应该是一个'int'(除此之外,可以检查'EOF',并且为了便于阅读和理解,应该检查''\ n' – user3629249
:1)遵循以下公理: *每行只有一条语句和(最多)一条语句的变量声明。* – user3629249
发布的代码只会提示用户一次输入一行(并且似乎期望用户能够'精神'读取'程序知道他们什么时候进入下一行被搜索, – user3629249