Why does this accept invalid input?

前端 未结 5 2177
一个人的身影
一个人的身影 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 10:22

    If you want to be able to detect an error with the user's input, such as a line not being a valid decimal integer, then you could do the following:

    • Read the input into a buffer using fgets(buffer, size, stdin)
    • Use strtoul(buffer, &endptr, 10) to parse the buffer as a decimal integer (base 10), where endptr is a char*
    • endptr will point to the first invalid character in buffer, ie. the character after the last one which was successfully parsed
    • Now if *endptr == '\0', ie. endptr points to the end of buffer, the whole string was parsed as a valid decimal integer

提交回复
热议问题