How to test input is sane

后端 未结 6 1125
一个人的身影
一个人的身影 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

    0 讨论(0)
  • 2020-12-11 12:03

    You can use like:

    if( scanf("%d%d",&a,&b) == 2)
    {
       //two integer values has been read successfully
       //do your stuff here
    }
    else
    {
       //Wrong input
    }
    
    0 讨论(0)
  • 2020-12-11 12:12

    you can test this one.

    #include <stdio.h>
    
    int main(void)
    {
        int a, b, c;
    
        printf("Enter two numbers to add\n");
        scanf("%d%d",&a,&b);
    
        if(scanf("%d%d",&a,&b) == 2)
        {
            c = a + b;
            printf("Sum of entered numbers = %d\n",c);
        }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 12:13

    User input is evil. Parse per:

    (optional whitespace)[decimal int][whitespace][decimal int](optional whitespace)
    

    strtol() and family have better error handling than scanf().
    Coda: Best to handle user input in a helper function. Break into 2 parts: I/O and parsing.

    #include <ctype.h>
    #include <errno.h>
    #include <limits.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    // return 1 (success), -1 (EOF/IOError) or 0 (conversion failure)
    int Readint(const char *prompt, int *dest, size_t n) {
      char buf[n * 21 * 2]; // big enough for `n` 64-bit int and then 2x
    
      fputs(prompt, stdout);  // do not use printf here to avoid UB
      fflush(stdout); // per @OP suggestion
      if (fgets(buf, sizeof buf, stdin) == NULL) {
        return -1;
      }
      const char *p = buf;
    
      while (n-- > 0) {
        char *endptr;
        errno = 0;
        long l = strtol(p, &endptr, 10);
        if (errno || (p == endptr) || (l < INT_MIN) || (l > INT_MAX)) {
          return 0;
        }
        *dest++ = (int) l;
        p = endptr;
      }
    
      // Trailing whitespace OK
      while (isspace((unsigned char) *p)) p++;
      // Still more text
      if (*p) return 0;
      return 1;
    }
    
    int main() {  // for testing
      int Result;
      do {
        int dest[2] = { -1 };
        Result = Readint("Enter two numbers to add\n", dest, 2);
        printf("%d %d %d\n", Result, dest[0], dest[1]);
      } while (Result >= 0);
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 12:21

    Also you can do this to prevent anything after second number

    int a,b;
    char c;
    if( scanf("%d%d%c", &a, &b, &c) == 3) {
        if (c == '\n') {
            puts("good");
        }
    } else {
        puts("bad");
    }
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 12:23

    A simple way would be,

    int a=0, b=0, c=0;
    

    initialise them to 0

    Additionally, the check suggested by Midhun is good to check if there are two inputs.

    0 讨论(0)
提交回复
热议问题