验证 scanf 中的最大整数 [英] Validate max integer in scanf

查看:54
本文介绍了验证 scanf 中的最大整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 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.

注意建议使用 atoisscanf 执行最终转换的响应.这些函数都没有防止溢出.

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

这篇关于验证 scanf 中的最大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆