Why does this accept invalid input?

前端 未结 5 2174
一个人的身影
一个人的身影 2020-12-22 09:52

I have a triangle program in c

#include 

// A function which decides the type of the triangle and prints it
void checkTriangle(int s1, int s         


        
5条回答
  •  无人及你
    2020-12-22 09:59

    If you really want each number on a separate line of input, and for the whole of the line to be valid number or space, then you probably need to forget scanf() and family and use fgets() and strtol() instead.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    static int read_side(void)
    {
        char buffer[4096];
        if (fgets(buffer, sizeof(buffer), stdin) == 0)  // EOF
            return -1;
        char *end;
        errno = 0;
        long result = strtol(buffer, &end, 10);
        if (result < 0 || errno != 0) // Neither errors nor negative numbers are allowed
            return -1;
        if (end == buffer)     // Nothing was convertible
            return -1;
        while (isspace(*end))
            end++;
        if (*end != '\0')      // Non-spaces after the last digit
            return -1;
        if (result > INT_MAX)  // Result too big for `int`
            return -1;
        return result;
    }
    

    (If you needed to accept any valid int value but distinguish errors, then you'd pass in a pointer to the function and return -1 on error or 0 on success, and assign the safe result to the pointer.)

    Yes, it really is that fiddly to do the job properly. And yes, analyzing the result of strtol() is as tricky as that; you do have to be very careful. (And there's an outside chance I've forgotten to check for a detectable error condition.) And no, I don't think you can do the equivalent job with scanf() et al; in particular, the behaviour on overflow with scanf() is undefined.

提交回复
热议问题