有没有办法限制 C 中的 scanf?

Is there a way of limiting scanf in C?

我正在尝试为链表使用编写一个正确的控制台应用程序,因此我需要在无限循环中扫描多个命令,并根据 switch case 选项做一些事情。所以我正在为此使用 scanf 但问题是当下一行不包含数字时它循环并开始打印甚至不打印默认值。

`while(1)
    {
            printf("Enter a number of a command.\n");
            scanf("%d",&command);
            switch(command)
            {
            case -1:
            ....
            default:
                  printf("Reenter command.\n");
                  break;
            }
    }

当我读取无限量的数据堆栈时,它似乎被重写了。我知道我必须限制符号读取的数量,但不明白如何以正确的方式做到这一点。

在 Ubuntu 18.04.2 LTS

上使用 gcc 版本 5.4.0 (GCC)、c99

我没有足够的声誉来发表评论,但这可能是您要找的。还要尝试更具描述性。我已经粘贴了你的代码,我能发现的唯一问题是,当你在没有插入数字(即字母)的情况下按回车键时,它会跳过。这应该可以解决它:

int readInt(const char *message, int min, int max){
    int num, control;
    do{
        printf("%s (%d a %d) :", message, min, max);
        control = scanf ("%d", &num);
        cleanBufferStdin();  
        if (control == 0)
        {
            printf("You should enter a number \n");
        }
        else{
            if(num<min || num>max)
            {
                printf("Number is invalid.\n");
            }
        }
    }  
    while(num<min || num>max || control ==0);

    return num;
}
void cleanBufferStdin(void)
{
    char chr;
    do
    {
        chr = getchar();
    }
    while (chr != '\n' && chr != EOF);
}

我编码了一点,并且在对你的问题的另一种解释中(这个不仅检测你是否刚刚按下回车键,而且如果你没有输入整数,我不检查负数是否有效)我使用了这个函数:

//DONT FORGET TO #DEFINE WRONG_REQUEST_MACRO "SOME MESSAGE"
void readString(const char message*, char arrayChars *, int maxChars){
    int stringSize;
    unsigned char flag=0;
    do{
        flag =0;
        printf("%s", message);
        fgets(arrayChars, maxChars, stdin);
        
        
        stringSize = strlen(arrayChars);
        if (stringSize == 1){
            printf("[INFO]Empty request. You just pressed ENTER.\n"); 
            flag=1;
        }
        if (atoi(arrayChars)==0&&arrayChars[0]!=0){
            printf("[INFO]You didn't enter a number.\n");
            flag=1;

        }
    } while (flag == 1);

    if (arrayChars[stringSize - 1] != '\n'){
        clearBuffer(); 
    }else{
        arrayChars[stringSize - 1] = '[=11=]'; 
    }

    while (strchr(arrayChars, '\'') != NULL || strchr(arrayChars, '?') != NULL || strchr(arrayChars, '*') != NULL || strchr(arrayChars, '\"') != NULL){
        printf("%s ' %s '", WRONG_REQUEST_MACRO, arrayChars);
        break;
    }
}

应该这样使用

int command;
char message[20];//yes this could be used with a char pointer but lets assume op doesnt know how to allocate memory or work with char pointers it wouldn't change that much but if he does know how to do it he will promptly change

readString("something something i suppose\n",message,20); 
command=atoi(message);

欢迎最后一个,虽然它充满了调试“重复”应该可以工作