Im trying to replace any instance of the letter x with a space. The code only works for the first word, however. Is there a way that I can get it to replace any instance of the letter x for multiple words?
1 2 3 4 5 6 7 8 9
void replaceX()
{
string str;
cout<<"Please enter a word containing the letter x"<<endl;
cin>>str;
replace( str.begin(), str.end(), 'x', ' ' );
cout<<str<<endl;
}
I tried that and when I display it doesnt let me input anything. Then I tried this and it doesnt display anything when i cout
1 2 3 4 5 6 7 8 9
void replaceX()
{
string str;
cout<<"Please enter a word containing the letter x"<<endl;
getline(cin, str);
cin.ignore();
replace( str.begin(), str.end(), 'x', ' ' );
cout<<str<<endl;
}
I'm guessing that in your program there are other uses of cin >> before you reach this point. The problem is not in this code as such, but is due to a trailing newline character remaining in the input buffer as a result of that previous activity.
Please let me know if I'm on the wrong track.
The solution is to clear the newline before calling this function.
1 2
cin.ignore(1000, '\n');
replaceX();
In my opinion it is inappropriate to put the ignore() inside function replaceX() because it won't always be needed, it is only required because of some other use of cin. At least that's my guess as to the most likely scenario.