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!

Recommended Answers

All 6 Replies

I think you will have to use a stream manipulator for that, I forget which one, maybe std::ios::fixed or std::ios::setprecision. They're in <iomanip>.

http://www.cplusplus.com/reference/iostream/manipulators/

You can set the output stream to display leading zeroes, but my question is why do you want the zero to be shown?

It does that because the number extracted is in base 10.

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;

leading zeros should be omitted in normal cases i think

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.