C++ C++;s、 replace函数不输出空格

C++ C++;s、 replace函数不输出空格,c++,string,function,replace,C++,String,Function,Replace,我正在尝试解决为什么一个简单的程序用“是”和“否”替换“是”不起作用。我的结论是,在“是”和“否”中有一个空格会导致这个问题。是否有办法使该程序与s.replace功能一起正常工作 谢谢 string s = "yes this is a program"; while (s.find("yes") != string::npos) { s.replace(s.find("yes"), 3, "yes and no"); } 编辑:下面是完整的程序,带有控制台输入字符串 int m

我正在尝试解决为什么一个简单的程序用“是”和“否”替换“是”不起作用。我的结论是,在“是”和“否”中有一个空格会导致这个问题。是否有办法使该程序与s.replace功能一起正常工作

谢谢

string s = "yes this is a program";


while (s.find("yes") != string::npos) {
    s.replace(s.find("yes"), 3, "yes and no");
}
编辑:下面是完整的程序,带有控制台输入字符串

int main() {
        string s;
        cout << "Input: ";
        getline(cin, s);


        while (s.find("yes") != string::npos) {
            s.replace(s.find("yes"), 3, "yes and no");
        }

        cout << s << endl;

    return 0;
}
intmain(){
字符串s;

cout就目前情况而言,首先是:

是的,这是一个节目

它在其中查找
yes
,然后替换它,这样您就可以得到:

是和否这是一个程序

然后再次搜索并替换:

是、否、否这是一个程序

这可能足以让问题变得显而易见:因为替换包含要替换的值,所以进行替换不会让它接近完成

为了在每次替换后的某个时间点完成搜索,我们可能希望在替换结束后开始下一次搜索,而不是从字符串的开头重新开始,一般顺序如下:

string::size_type pos = 0; // start from the beginning

std::string replacement = "yes and no";

while ((pos=s.find("yes", pos)) != string::npos) {
    s.replace(pos, 3, replacement);

    // adjust the starting point of the next search to the end of the
    // replacement we just did.
    pos += replacement.length(); 
}

为什么要在
时使用
?这是一个无限循环…在替换后向输出s添加一个cout,看看您是否能找出错误所在。(为了将来参考,将不起作用不是一个传达任何意义或有任何价值的问题描述,除非您特别解释您预期会发生什么以及发生了什么。)我正在从控制台获取此程序的输入。我定义有限字符串是为了在此处提问。然后您选择了错误的模拟文本,因为它显然引入了不同的问题。请阅读。然后再次阅读我的注释。无论输入来自何处,它都适用。