How to test input is sane

后端 未结 6 1127
一个人的身影
一个人的身影 2020-12-11 11:38

Consider the following simple C program.

//C test

#include

int main()
{
   int a, b, c;

   printf(\"Enter two numbers to add\\n\");
   scan         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-11 12:00

    You can use the following macro

    #define SCAN_ONEENTRY_WITHCHECK(FORM,X,COND) \
    do {\
        char tmp;\
        while(((scanf(" "FORM"%c",X,&tmp)!=2 || !isspace(tmp)) && !scanf("%*[^\n]"))\
                || !(COND)) {\
            printf("Invalid input, please enter again: ");\
        }\
    } while(0)
    

    and you call it in this way in the main

    int main()
    
    {
        int a, b, c;
    
        printf("Input first integer, valid choice between 0 and 10: ");
        SCAN_ONEENTRY_WITHCHECK("%d",&a,(a>=0 && a<=10));
    
        printf("Input second integer, valid choice between 0 and 10: ");
        SCAN_ONEENTRY_WITHCHECK("%d",&b,(b>=0 && b<=10));
    
        c = a + b;
        printf("Sum of entered numbers = %d\n",c);
        return 0;
    
    }
    

    for more detail concerning this macro please refer to: Common macro to read input data and check its validity

提交回复
热议问题