neuromancer
neuromancer

Reputation: 55579

Splitting a c++ string into two parts

I'm trying to split a string that contains "|" into two parts.

if (size_t found = s.find("|") != string::npos)
{
    cout << "left side = " << s.substr(0,found) << endl;
    cout << "right side = " << s.substr(found+1, string::npos) << endl;

}

This works with "a|b", but with "a | b", it will have "| b" as the right side. Why is that? How can this be fixed?

Upvotes: 4

Views: 11135

Answers (1)

James McNellis
James McNellis

Reputation: 355307

size_t found = s.find("|") != string::npos

This is a declaration; it gets parsed as

size_t found = (s.find("|") != string::npos)

So, found will always be 1 or 0. You need to declare found outside of the condition and use some parentheses:

size_t found;
if ((found = s.find("|")) != string::npos)

Upvotes: 14

Related Questions