出於某種原因,一旦我輸入要搜索的字符,主循環將終止,但目的是爲了能夠輸入一行然後搜索一個字符你輸入一個空行(不輸入任何內容)。基本上我會想無限地做第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