Validate max integer in scanf

前端 未结 4 1734
独厮守ぢ
独厮守ぢ 2020-12-15 11:20

I want to read a int from stdin but I want to validate if the user exceeds the int max value. How can I do it?

int n;
scanf(\"%d\", &n);
<
4条回答
  •  既然无缘
    2020-12-15 12:04

    The only way to convert a string representation of a number to the actual value and to watch for overflow is to use functions from strto.. group. In your case you need to read in a string representation of the number and then convert it using strtol function.

    Beware of responses that suggest using atoi or sscanf to perform the final conversion. None of these functions protect from overflow.

提交回复
热议问题