Reputation: 223
I need to use a high Number in my program. Here is an minimum example that shows the problem. It just reads in a number and gives out the number again.
using namespace std;
#include <iostream>
#include <stdlib.h>
int main(int argc, char* argv[])
{
double
N = atoi(argv[1]);
cout << N << endl;
return 0;
}
Everything works fine till 10^9 If I take 10^10 as input the result is 1.41007e+09. I just don't know why this is the case. I already tried the following:
Upvotes: 0
Views: 1112
Reputation: 1250
The input 10^10 goes beyond the maximum limit of an integer that is 2147483648 and 10^9 is well within the limit.
Following code can be useful.
using namespace std;
#include <iostream>
#include <stdlib.h>
int main(int argc, char* argv[])
{
long long N = atoll (argv[1]);
cout << N << endl;
return 0;
}
Upvotes: -1
Reputation: 775
Using atoi on the number greater than INT_MAX will cause the resultant value to start from the negative value INT_MIN.
Try using atoll function. It is in . But this is defined in C++11. So, if your compiler is not up-to-date than it will throw an error.
If the value is again quite large (greater than 8 bytes), then I would suggest you to use external libraries.
Upvotes: 0
Reputation: 141586
Using atoi
when the resulting value would be outside the bounds of int
(i.e. greater than INT_MAX
or less than INT_MIN
) causes undefined behaviour.
This is a good reason to not use atoi
. The alternatives strtol
and strtoul
from the C library have well-defined behaviour for all inputs.
The C++11 function std::stoi
also has well-defined behaviour (it throws an exception if the value is out of range). istream::operator>>(int&)
is also well-defined but it has some finicky details relating to the fact that streams can't "look ahead".
Upvotes: 2