Reputation: 3
I have a string of the form std::string str = "1001 0104 2325 9999" and I need to store these four substrings seperated by spaces in integers . Is there an elegant way to do this task like there is with strings in C(using sscanf) ? This is not a homework question .
Upvotes: 0
Views: 1880
Reputation: 490108
The cleanest way would probably be to use a stringstream with an istream_iterator, something like this:
std::string str = "1001 0104 2325 9999";
std::istringstream in(str);
std::vector<int> numbers {
std::istream_iterator<int>(in),
std::istream_iterator<int>()
};
// just to show what we did:
for (int i : numbers)
std::cout << i << "\n";
Note that there is a little bit of ambiguity in the input you provided: it's not clear whether you intent the 0104
to be decimal or octal (as a leading zero would cause it to be interpreted in source code). The code I've written above interprets it as decimal. If you want a leading 0
to mean octal (and leading 0x
to mean hexadecimal) you can do that (at least if memory serves) by setting the base for the conversion to 0.
Upvotes: 1