Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I check integer overflow in C/C++?

Tags:

c++

c

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" .

Note that, I have already checked How to detect integer overflow? . But the question is different from my one.

like image 863
Md. Al-Amin Avatar asked Dec 25 '22 18:12

Md. Al-Amin


1 Answers

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.

UPDATE

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

like image 193
asalic Avatar answered Jan 07 '23 01:01

asalic