Removing a char

I have a string which is string s = "Hello:Brave:New:World";
We are supposed to used a while loop to make a new line where ever there is a ":" and then remove the colons. My professor wants me to use two unsigned ints which is confusing me somewhat. This is what I have so far:

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
/*
	Classwork1
	2.1.11
*/

#include<iostream>
#include<string>
using namespace std;

int main()
{	
	unsigned int found(0), temp(0);
	string s = "Hello:Brave:New:World";
	string ss;
	//write a loop to print each word on own line without colon
	while(found < s.size())
	{
		found = s.find(":", found-temp);
		ss = s.substr(temp,(found-temp));
		cout << ss << endl;
		temp = found + 1;
	}
	cout << endl;
	return 0;
}


Here is what I get when I run it:
Hello
Brave:New:World

Press any key to continue . . .


Thanks for the help.
Desk test:
Initial state
s="Hello:Brave:New:World";
found=0, temp=0
1
2
3
4
5
6
found = s.find(":", found-temp); //found-temp=0 -> found=5
ss = s.substr(temp,(found-temp)); //ss="Hello"
cout << ss << endl;
temp = found + 1;//temp=6
//next loop
found = s.find(":", found-temp); //found-temp=-1 but it is unsigned so max_int -> found=string::npos 

Last edited on
Can you explain that post a little more please? Do I need a different loop? Do I just need to add what you added (the last line)?
closed account (z05DSL3A)
I changed the names to make them more meaning full and two minor changes to the logic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<string>
using namespace std;

int main()
{	
	unsigned int start_point(0), end_point(0);
	string s = "Hello:Brave:New:World";

	//write a loop to print each word on own line without colon
	while(end_point < s.length() )
	{
		end_point = s.find(":", start_point);
		cout << s.substr(start_point, end_point - start_point ) << endl;
		start_point = end_point + 1;
	}
	cout << endl;
	return 0;
}
that was a simulation of your code.
found = s.find(":", found-temp); that's your error. temp is bigger than found, but they are unsigned so
1
2
temp-found == 1;
found-temp == 4294967295;
so s.find tells you that it can't find the substring.
Thank you Grey Wolf.
Topic archived. No new replies allowed.