Hey guys , i haing a problem with using stringstream and atoi . I am trying to conert a string to in integer

When using stringstream

string d = "033116";
     int b = 0;
   
        stringstream ss (d);
         ss >> b ;

When using atoi

string d = "033116";
     int b = 0;

         b = atoi(d.c_str();

For some reason , when i cout my result out , the result displayed will be "33116". For some reason , it will not read "0" as in integer. Is there any way i can fix this issue. Thanks!

Because an integer can span over several characters (like 1312, i.e. 4 characters), the stringstream finds, by default, the first and longest sequence of characters that constitutes a valid number. And discarding leading 0 characters because in any base, leading zeros are meaningless. But, of course, if you have only a zero, then zero will be the integer returned.

Using io manips, you can probably set it to use a fixed size of 1 character for the integer. However, if you are looking for extracting each digit of the number, then I would just do:

string d = "033116";
int b[6];
b[0] = d[0] - '0';
b[1] = d[1] - '0';
b[2] = d[2] - '0';
b[3] = d[3] - '0';
b[4] = d[4] - '0';
b[5] = d[5] - '0';

std::cout << "digits are: " << b[0] << b[1] << b[2] << b[3] << b[4] << b[5] << std::endl;

You can display leading 0s like this (include <iomanip> header file cout << std::setfill('0') << std::setw(6) << b << '\n';

Edited 5 Years Ago by Ancient Dragon: n/a

You can display leading 0s like this (include <iomanip> header file cout << std::setfill('0') << std::setw(6) << b << '\n';

i think he consider 0 and the following digits to be two different integers.

This article has been dead for over six months. Start a new discussion instead.