while循环不会按预期继续

时间:2017-04-02 01:59:23

标签: c arrays while-loop fgets garbage

由于某种原因,一旦我输入要搜索的字符,主要的while循环终止,但目的是让你能够输入一行,然后搜索一个字符,直到你输入一个空白行(不输入任何内容) 。基本上我会想无限制地执行第1步和第2步,直到我输入任何内容并按下回车键。为什么这不起作用?感谢任何人的帮助!

另外,还有一个小问题,如何在输入字符进行搜索后清除任何垃圾?

#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;
}

我包含了我的整个代码,如果这不是太烦人,我可以尝试制作一个更简单的问题版本,如果这会有所帮助。我认为发布整个代码可能对回答这个问题更有用。

再次感谢,欢呼!

2 个答案:

答案 0 :(得分:2)

repo/docs

这应该有效

答案 1 :(得分:1)

发布代码的主要问题是用户必须按enter才能将search字符输入程序。但是,对getchar()的调用仅消耗一个char,因此它不使用换行序列。

要解决此问题,请在循环中调用getchar(),直到char为EOF或&#39; \ n&#39;清除任何/所有剩余垃圾的stdin

然后回到循环的顶部