I have a function recieving a string, which is a pair of comma delimited integers in a fashion such as "12,4". How can I parse the integers out of this string?
Asked
Active
Viewed 3,777 times
4 Answers
2
std::getline
implements the basic "split" functionality (I don't see it mentioned in the first few answers at the other question.)
vector< int > numbers;
istringstream all_numbers_iss( "12,4" );
string number_str;
int number;
while ( getline( all_numbers_iss, number_str, ',' ) // separate at comma
&& istringstream( number_str ) >> number ) {
numbers.push_back( number );
}

Potatoswatter
- 134,909
- 25
- 265
- 421
-
Shouldn't the extraction from the `istringstream` fail for passing a const as a reference for the lhs? – wilhelmtell Apr 03 '11 at 03:34
-
-
-
@wilhelm: It doesn't matter; the rvalue isn't converted to a reference. – Potatoswatter Apr 03 '11 at 04:12
0
Depends whether or not you can depend on the incoming data being valid. If you can, I'd do:
#include <cstdlib>
#include <utility>
#include <string>
std::pair<int, int> split(std::string const& str)
{
int const a = std::atoi(str.c_str());
int const b = std::atoi(str.c_str() + str.find(',') + 1);
return std::make_pair(a, b);
}

ildjarn
- 62,044
- 9
- 127
- 211
-
1@rubenvb : I'm not clear what you mean by that. `atoi` is a C API and consequently cannot throw exceptions. – ildjarn Apr 03 '11 at 15:31
-
ok, bad wording. What I meant was that when it chokes it produces nonsense: `atoi` on a non-integer gives 0, just like `atoi` on 0 gives 0. And if the input needs validation, you might as well use the type-safe `stringstream` alternative. – rubenvb Apr 03 '11 at 16:51
-
@rubenvb : Which is why I specifically said "If you can (depend on the incoming data being valid)". If the data needs validation, I agree with you that `atoi` is completely inappropriate. – ildjarn Apr 03 '11 at 16:52
-
agreed, but it's still an awful function to use in C++. For example, see the discussion resulting from this answer: http://stackoverflow.com/questions/5017001/like-atoi-but-to-float/5017022#5017022 – rubenvb Apr 03 '11 at 16:54
-
1@rubenvb : Possibly, but given that I explicitly called out the caveat with using it, I don't think a downvote is warranted. Personally, I use boost.spirit.qi for this sort of thing, but I hate using it for answering trivial questions like this because it tends to raise more questions than it answers. – ildjarn Apr 03 '11 at 16:55