清除 fgets 缓冲区

问题描述 投票:0回答:1

我的代码有问题。

int startProg()
{
    char *method;
    method= malloc(30*sizeof(char));
    int isInteger=0;
    int num;
    do{

        printf("Seleziona il metodo \n");
        fgets(method,30,stdin);
        //check if there is just one char inside 
        if (method[1]!= 10)
        {
            printf("Inserire solo un carattere  \n");
        }else{

            if (method[0]>=49&&method[0]<=52){

                 switch (method[0]){
                    case '1':
                        num=1;
                        break;
                    case '2':
                        num=2;
                        break;
                    case '3':
                        num=3;
                        break;
                    case '4':
                        num=4;        
                        break;
                }
                isInteger=1;
                //check the option choose
            }else{
                printf("Inserire un carattere valido\n");
            }
        }
    }while(isInteger==0);
    free (method);
    return num;
}

这个想法是接收用户输入,检查是否是1到4之间的数字,检查值是然后返回该值。 唯一的问题是,当我插入一个大于 fget 值的数字时,我的代码会循环多次。

我必须清理缓冲区,并且我需要我的代码是可移植的。 有人出主意吗? 谢谢

c fgets
1个回答
0
投票

您需要对所有数字进行 if 语句检查

if (method[0]>=48&&method[0]<=57){

(或者这种更易读的方式:

if (method[0]>='0'&&method[0]<='9'){
© www.soinside.com 2019 - 2024. All rights reserved.