C 清除输入缓冲区/垃圾?

C 清除输入缓冲区/垃圾?,c,while-loop,user-input,fgets,garbage,C,While Loop,User Input,Fgets,Garbage,在这个程序中,当我输入8个字符时,整个程序都会出错,我认为这与在输入大于或等于大小的字符时清除输入缓冲区有关,我如何使它清除用户可能输入的任何字符溢出? 谢谢你的帮助 #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,charsF

在这个程序中,当我输入8个字符时,整个程序都会出错,我认为这与在输入大于或等于大小的字符时清除输入缓冲区有关,我如何使它清除用户可能输入的任何字符溢出? 谢谢你的帮助

#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;
}
#包括
#定义大小8
int CharIsAt(字符*pStr,字符ch,字符loc[],字符mLoc);
内部主(空){
字符数组[大小],搜索;
int find[SIZE],i,charsFound;
printf(“输入一行文本(要退出的空行):”;
while(fgets(array,SIZE,stdin)!=NULL&&array[0]!='\n'){//循环,直到没有输入任何内容为止
printf(“输入要搜索的字符:”);
search=getchar();
charsFound=CharIsAt(数组、搜索、找到、大小);
printf(“输入文本:”);
fputs(数组,标准输出);//打印输入的文本
printf(“正在搜索的字符:%c\n”,search);//打印正在搜索的字符
printf(“在%d个位置找到的字符)。\n”,charsFound);//打印找到的字符数
//打印相对于行首找到的字符的位置

对于(i=0;i)您需要检查该行是否以
\n
结尾。如果不是,这意味着用户输入的字符太多。然后您需要读取并放弃输入,直到看到
\n
。请参阅此问题
搜索=getchar();
此处的换行符仍然保留。