我怎么能检查在C / C ++整数溢出? [英] how can I check integer overflow in C/C++?

查看:151
本文介绍了我怎么能检查在C / C ++整数溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何确定C / C ++溢出。如果我的整数输入为9999999999999999999999,这是一个非常大的数字,如果我运行低于code,我会得到一个错误的输出。

I want to know how to determine overflow in C/C++. if my input for integer is 9999999999999999999999 , It is a very big number and if I run the below code I will get a garbage output.

#include <stdio.h>

int main(){
    int a;
    scanf("%d",&a);
    printf("%d",a);
    return 0;
}

有没有办法知道,如果输入的是一个很大的数字,我可以输出输入太大了。

Is there any way to know , if the input is a big number, I can output "Input is too big" .

请注意,我已经检查检测整数溢出的最佳方式在C / C ++ 。但问题是,从我的不同。

Note that, I have already checked Best way to detect integer overflow in C/C++ . But the question is different from my one.

推荐答案

在你的情况,请阅读字符串输入,然后根据长度,再做决定。可以连接code字符串整数的限制,长长等,如果输入具有长度等于或小于的你的字符串限制之一(数字数),移动一个与该比较,如果它是较小不是字符串重的限制presentation,你可以放心地将其转换为整数类型。

In your case, read the input in a string and then, depending of the length, make a decision. You can encode in string the limits of integer, long long etc and if the input has the length (the number of figures) equal or less than one of your string limits, move one with the comparison and if it is smaller than the string representation of a limit, you can safely convert it to an integer type.

更新

或者如果你preFER你可用在C中流作业++作为大卫·布朗建议...

or if you prefer you can use stream operators in C++ as David Brown suggested...

这篇关于我怎么能检查在C / C ++整数溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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