0

In this program, when I enter 8 characters, it screws up the whole program, and I think it has something to do with clearing the input buffer when you enter more than or equal to SIZE characters, how do I make it so that it clears any overflow of characters a user may enter? Thanks for any help!

#include <stdio.h>
#define SIZE 8
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    printf("Enter a line of text(empty line to quit): ");
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout); //Prints text inputted
        printf("Character being searched for: %c\n",search); //Prints character being searched for
        printf("Character found at %d location(s).\n",charsFound); //Prints # of found characters
        //Prints the location of the characters found relative to start of line
        for (i=0;i<charsFound;i++)
            printf("'%c' was found at %d\n",search,found[i]);
        if (fgets(array,SIZE,stdin)==NULL) //Makes loop re-prompt
            break;
        printf("\nEnter 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;
}
King Sutter
  • 61
  • 2
  • 4
  • 11
  • 1
    You need to check whether the line is terminated with `\n`. If not, this means the user has entered too many characters. You then need to read and discard the input until you see `\n`. – n. m. could be an AI Apr 02 '17 at 04:43
  • See this question [Clear input buffer after fgets() in C](http://stackoverflow.com/questions/38767967/clear-input-buffer-after-fgets-in-c) – nnn Apr 02 '17 at 04:46
  • `search=getchar();` The newline here remains. – BLUEPIXY Apr 02 '17 at 09:22

0 Answers0