std::string::npos ??

Just overcame a huge obstacle in my code - took a while so I'm worn out. Anyway, in solving this mystery obstacle I used the code below. What it does is will check to see if there is white space in the buffer - if there is it'll ignore it. Then it'll check if there's an 'a' in the buffer - if there is, it'll assign y to equal a and then jump to another part of the code. I know HOW it works - I don't understand WHY it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	u = std::cin.peek();

	if (u.find(' ') != std::string::npos)
	{
		std::cin.ignore(std::numeric_limits<int>::max(), ' ');
	}

	o = std::cin.peek();

	if (o.find('a') != std::string::npos)
	 {
		 y = a;
		 goto Operation;
	 }


Now my question is regarding the "!= std::string::npos" part. I read that the npos means the "greatest value possible" - but how does that make this if statement work like that? I understand what it does - I don't understand why it does it. I don't even really know how to interpret the if statements - I've used them without understanding WHY they function. "o.find('a') looks for 'a', but does it signal when it's found it ( I ask because if(o.find('a') by itself doesn't work ). And how can o.find('a') be not equal to the greatest possible value?? I don't understand it - Hope someone can clarify why this code works the way it does - Thanks!
Last edited on
You're just overthinking it. Forget about everything you've done today or what you've read in the documentation about std::string and just focus on the following sentence:

some_string.find('a') will EITHER return the position of the first appearance of 'a' in some_string if 'a' appears at least once in some_string, OR it will return a value that is equal to std::string::npos if 'a' does not appear at all in some_string.

So logically:
IF o.find('a') == std::string::npos THEN o doesn't contain 'a'.
IF o.find('a') != std::string::npos THEN o contains 'a' at least once.

The exact value of std::string::npos is entirely irrelevant. What's important is that std::string::find() will never return that value if the specified character is found in the string.
Ah! i see now, that makes perfect sense. The value of npos IS the highest amount possible - but that's not what's important. What is important is that .find will send that same exact value if 'a' isn't found - hence why when o.find('a') != npos means that 'a' was found. When 'a' is found, it'll return the position - which wont be anywhere near the npos value - making it true and then vice versa (if 'a' isn't found the output positions will equal the npos value).

Thanks a lot helios ! You're always knowledgeable and helpful - I'm lucky to have such competent help.
Last edited on
Topic archived. No new replies allowed.