Arthur P. Arthur P. - 6 months ago 17
C++ Question

Replace part of a string with another string (missing first string)

cin >> "You are very good."

#include <iostream>
#include <string>

using namespace std;

int main()
string s;
cin >> s;

while (getline(cin, s))
while (s.find("bad")!= string::npos)
s.replace(s.find("bad"), 3, "good");
cout << s << endl;

return 0;

cout << "are very good."

Where is first word "You"? How should look correct code?


cin >> s; before the loop is reading the first word of the line and removing it from the input stream. Then getline(cin, s) reads the rest of the line. So the first time through the loop, s is just are very bad. You then replace bad with good, and the result is are very good.

There doesn't seem to be any reason for the cin >> s; line, so just remove it.