Question

Recently I've been working on writing snippets for my finals. One of the common task is to divide a string (std::string) into words. In some cases these strings can contain integers.

I wrote a snippet:

#include <sstream>
#include <iostream>
#include <vector>
using namespace std;

int main(void)
{
string str="23 005 123";
vector<int>myints;
istringstream iss(str);

string word;

while(iss>>word)
{
    int a;
    istringstream(word)>>a;
    myints.push_back(a);
}

for (vector<int>::iterator it=myints.begin();it!=myints.end();++it)
    cout<<*it<<" ";

} 

It works, although there's a problem. I get 5 from str instead of 005. It seems that VC++ shrinks all the zeroes. How can avoid it using only C++ functions (not strtok from string.h/cstring)?

I get it both on MS VC++2008 and gcc.

Thanks!

Was it helpful?

Solution

If you need to remember the number of leading zeros from the input and print it with exactly the same number of leading zeros later, the only option is not storing as an int. You could, for example, turn your vector<int> into a vector<string>.

Alternatively, you could use a vector< pair<int,string> >, which keeps the integer you want along with the original string representation.

Finally, if you don't care about the actual number of leading zeros that were in the input, but simply want everything to be padded with leading zeros to equal length, you can use setfill and setw :

cout << setfill('0') << setw(5) << 25;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top