清除输入缓冲区/垃圾?

时间:2017-04-02 04:11:32

标签: c while-loop user-input fgets garbage

在这个程序中,当我输入8个字符时,它会搞砸整个程序,我认为当你输入大于或等于SIZE字符时清除输入缓冲区有什么关系,我怎么做到这一点它清除用户可能输入的任何字符溢出? 谢谢你的帮助!

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

0 个答案:

没有答案