Program not out putting last string

Hi I created a program that censors every 4 letter word in a sentence entered by a user. However for some reason if you type "Hi my name is Bobby" the program will out put "Hi my **** is" however this problem does not occur if the last word entered by the user is a 4 letter word.

Any help is highly appreciated!

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>

using namespace std;

void censor(string x){

	int h=x.length();

	do{
		if((x.substr(0,x.find(" "))).length()!=4){
		cout<<x.substr(0,(x.find(" ")+1));

        h = h - (((x.substr(0,(x.find(" ")))).length())+1);

	    x.erase(0,(x.find(" ")+1));
		}

		else{
		   cout<<"****";
		   x.erase(0,4);
		   h=h-4; 
		}
		   
		   
	}while(h>0);
	cout<<endl;
}

int main(){

	string x;

	cout<<"Enter sentece to censor every 4 letter word: ";
	getline(cin,x);


	cout<<"Censored sentence: "<<endl;
	censor(x);

}
x.find(" ") will return std::string::npos when x is "Bobby". std::string::npos is the largest value that the return type of find can hold. When you add one x.find(" ")+1 the value will overflow and become the smallest value, which is zero because the type is unsigned. So in the last iteration you are printing x.substr(0, 0); (an empty string).
how do i fix that? take a way the +1?
Topic archived. No new replies allowed.