-1

Im suppose to create a loop that takes in a string input number and turn it to a integer variable so i could add 1 to the number and then turn it back to a string and print it out 5 times with 1 added to the number per print.The problem is, it only works up to 9 digits. if you put more then 9 then it starts giving other different numbers like -125346543.

if you put 9 digits 101010101. it will print it out 101010101 -> 101010106, but if you put 10 digits like 1010101010. it will print out -128764798 -> 128764804. I need it to print a least up to 13 digits

#include <iostream>
#include <string>
#include <sstream>

int main() {
    int l=0;
    int x=0;
    string nope;
    cout<<"please provide 13 digit code : ";
    cin>>nope;                                // ask for 13 digit code
for(i=0; i < 5 ; i++)
{
    stringstream geek(nope);                 // turn string to Int
    geek>>x;
    l = x + 1;                               // add 1 to Int
    stringstream ss;                         // turn it back to string
    ss << l;
    string q = ss.str();
    nope = q;
    cout<<nope;                              // prints out
}
james
  • 1
  • 1
  • You've reach "int" max value, try using a "long" instead, which is 64 bits instead of 32. https://stackoverflow.com/a/94608/62921 – ForceMagic Jan 31 '18 at 04:03

1 Answers1

1

The built in int types in C++ are usually 32 bit. This means they cannot store values larger than 2^31-1 (as the high bit is usually used for sign). (C++ requires it be at least 16 bits)

If you want infinite precision integers, you must use a library, not built in int directly.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524