简体   繁体   English

在 C 程序中用字符输入验证整数

[英]Validation of integer with character input in C program

I write this program to do validation of selection (integer type variable) that entered by users.我编写这个程序来验证用户输入的选择(整数类型变量)。 But the problem is after a valid input, the next invalid input (eg: character type variable) will not be stored in the integer variable (selection).但问题是在一个有效输入之后,下一个无效输入(例如:字符类型变量)不会存储在整型变量(选择)中。 How can I solve this?我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#pragma warning (disable:4996)

void main()
{
    int selection;
    while (1)
    {
        while (1)
        {
            printf("Enter Your Selection (0-4) > ");
            scanf("%d", &selection);
            rewind(stdin);
            if (!selectionCheck(&selection, 0, 4))
                printf("Invalid\n");
            else break;
        }
        printf("Success\n");
    }

    system("pause");
}

int selectionCheck(int *input, int min, int max)
{
    char str[100] = "";
    itoa(*input, str, 10);
    if (isdigit(str[0]))
    {
        if (*input < min || *input > max)
            return 0;
        else return 1;
    }
    else
    {
        return 0;
    }
}

Some notes: 1) You aren't checking the scanf() return value, and this is very usable: the negative return means that the entered characters can't be converted to int (because of "%d" format), and the return value equal 0 means that the input is empty (no characters entered).一些注意事项:1)您没有检查scanf()返回值,这非常有用:负返回意味着输入的字符无法转换为int (因为“%d”格式),并且返回值等于 0 表示输入为空(未输入字符)。

2) In case that the user entered wrong character(s) (not digit(s)), the input buffer will remain busy until you read it in other way. 2) 如果用户输入了错误的字符(不是数字),输入缓冲区将保持忙碌状态,直到您以其他方式读取它。 Good idea is to use additional scanf("%s") here to read any characters as string, so buffer will be empty after this call.好主意是在这里使用额外的scanf("%s")将任何字符读取为字符串,因此在此调用后缓冲区将为空。 Using rewind() is not enough here.在这里使用rewind()是不够的。

3) There is no need to additional checking of input in selectionChecking() for isdigit() , because "%d" format in scanf() doesn't allow to read anything else but number. 3) 无需额外检查selectionChecking()中的isdigit() ,因为scanf()中的“%d”格式不允许读取除数字之外的任何其他内容。

4) There is no need to pass pointer to selection value in selectionChecking() call - it will be enough to pass it as value. 4) 不需要在selectionChecking()调用中传递指向selection值的指针 - 将它作为值传递就足够了。

So, try this below:所以,试试下面这个:

// declaration of 'selectionCheck()'
int selectionCheck(int input, int min, int max);

void main()
{
    int selection;
    while (1)
    {
        while (1)
        {
            printf("Enter Your Selection (0-4) > ");

            int ret = scanf("%d", &selection);
            if (ret < 0) // invalid characters on input
            {
                printf("Invalid characters\n");
                scanf("%s"); // empty buffer, reading it as string and putting readed characters to nowhere ;)
                continue; // go to top of loop
            }

            if (ret == 0) // empty input
            {
                printf("No (empty) input\n");
                continue; // go to top of loop
            }

            // here 'ret' is greather than 0, so valid number was entered

            if (selectionCheck(selection, 0, 4)) // is value between 0 and 4 ?
                break; // yes, success, break current loop!

            printf("Invalid value\n");
        }

        printf("Success\n");
    }

    system("pause");
}

int selectionCheck(int input, int min, int max)
{
    if (input < min || input > max)
        return 0;
    else 
        return 1;
}

Of course, you can write 'selectionCheck()' more condensed:当然,你可以更简洁地写“selectionCheck()”:

int selectionCheck(int input, int min, int max)
{
    return (input < min || input > max) ? 0 : 1;
}

or simply:或者干脆:

int selectionCheck(int input, int min, int max)
{
    return (input >= min && input <= max);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM