Search code examples
carrayswhile-loopfgetsgarbage

The while loop doesn't continue as intended


For some reason, the while loop in main terminates once I enter a character to search, but the intention is for you to be able to enter a line and then a character to search until you enter a blank line (enter nothing). Basically I would want to do step 1 and step 2 infinitely until I type nothing and hit enter. Why doesn't this work? Thanks anyone for help!

Also, a little side question, how do I clear any garbage after a character is entered for searching?

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

I included my entire code if that's not too annoying, I can try and make a simpler version of the problem if that would help. I figured posting the entire code might be more useful for answering the question.

Thanks again, cheers!


Solution

  •    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){
            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]);
            if (fgets(array,SIZE, stdin)==NULL) break;
        }
        return 0;
    

    This should work