std::string .find()

Feb 20, 2013 at 6:08pm
So, for some reason I never bothered to learn about string functions. I've written some code to remove a word from a string which works fine. After the word has been removed, I'm trying to loop and search the text to remove any spaces left behind from the word removal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>

int main()
{
	std::cout << "Please enter some text:\n";

	std::string text;
	std::getline( std::cin, text, '\n' );
	
	std::cout << "\nThanks. You entered the following:\n";
	std::cout << text << '\n';

	std::cout << "\nNow, enter a word you wish to remove from the text you entered:\n";
	std::string word;
	std::getline( std::cin, word, '\n' );

	std::size_t nPos = text.find( word, 0 );

	if( nPos == -1 )
		std::cout << "\nSorry, the word you entered was not found\n";
	else
	{
		text.erase( nPos, word.length() );

		// Erase extra spaces.
		do
		{
			nPos = text.find( "  ", 0 );
			std::cout << nPos << '\n';

			text.erase( nPos, 1 );
		
		}while( nPos != -1 );

		std::cout << "\nHere is the text with the word removed:\n";
		std::cout << text << '\n';
	}

	return 0;
}


Within the do-while loop, line 29, finds all the spaces and erases one space, leaving the other.

The only problem is, when it's completed finding and erasing the double spaces, nPos( the return from find() ) is 4294967295. My understanding is, that when the find() function doesn't find what you're looking for, it should return -1.

Hopefully someone here can explain what's going on. Thanks! (:
Feb 20, 2013 at 6:12pm
No find returns a size_t which is an unsigned type, therefore it can't possibly return a value of -1. You should always compare the return value of std::string.find() to std::string::npos which is the value that find() returns on failure.



Feb 21, 2013 at 1:17pm
Ok, so I have it "working" without an infinite loop now. But I have a problem with it not searching properly.

1
2
3
4
5
6
	while( text.find( "  ", 0 ) == nPos );
	{
		//std::cout << nPos << '\n';

		text.erase( nPos, 1 );
	}


After line 18 in my original post, nPos doesn't seem to change. The word entered will get removed, then the extra space it leaves behind will also get removed.

But if I purposefully add 2 spaces either before or after the word erase location, nothing will happen to them.
Feb 21, 2013 at 1:40pm
That loop never update nPos. Maybe your intention was to write
1
2
3
4
5
6
while((nPos = text.find( "  ", 0 )) != std::string::npos);
{
	//std::cout << nPos << '\n';

	text.erase( nPos, 1 );
}
Feb 21, 2013 at 2:00pm
Ha! I cut/paste it wrong when I moved it!

Edit: I had a ';' at the end of the while-loop too! aha

And thanks!! Working great now!
Last edited on Feb 21, 2013 at 2:02pm
Topic archived. No new replies allowed.