问题描述
我想从 stdin 读取一个 int 但我想验证用户是否超过了 int 最大值.我该怎么做?
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);
scanf 读取十进制输入并存储在 int 中,导致溢出.我该如何检查和避免这种情况?
scanf reads the decimal input and stores in the int, causing overflow. How can I check and avoid this?
推荐答案
将数字的字符串表示形式转换为实际值并监视溢出的唯一方法是使用 strto..
中的函数代码>组.在您的情况下,您需要读取数字的字符串表示形式,然后使用 strtol
函数将其转换.
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.
注意建议使用 atoi
或 sscanf
执行最终转换的响应.这些函数都没有防止溢出.
Beware of responses that suggest using atoi
or sscanf
to perform the final conversion. None of these functions protect from overflow.
这篇关于验证 scanf 中的最大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!