4

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?

1 Answer 1

14
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) 
Sign up to request clarification or add additional context in comments.

6 Comments

Yet another operator lower than == in precedence. :p
Is there a way to put the declaration of found inside the if statement?
@wilhelmtell Not an operator. As James McNellis said, size_t found = ... is a declaration. The = is part of the grammar of the declaration, and is not an operator.
@Phenom Not immediately. But why would you want to, other than for obfuscation?
For optimal readability, I'd suggest size_t found = s.find("|"); if(found != string::npos) { ... }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.