C++ 如何使用string::replace方法写入文件?

C++ 如何使用string::replace方法写入文件?,c++,C++,假设我有一个代码: #include <iostream> #include <string> #include <fstream> using namespace std; int main() { string line,wantedString,newString; fstream subor("test.txt"); while (!subor.fail()) // read line from test.txt

假设我有一个代码:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string line,wantedString,newString;
    fstream subor("test.txt");
    while (!subor.fail())  // read line from test.txt
    {
        getline(subor,line);
        line.substr(line.find("?")+1);
        wantedString=line.substr(line.find("?")+1); // will take everything after '?' character till 
'\n'
    }
    cout<<"Enter new text to replace wantedString :";
    getline(cin,newString);

    // how to use string::replace() please ?
    /I tried this but does not work
    getline(subor,line);
    line.replace(wantedString,string::npos,newString); 
    return 0;
}
注意:文件中没有“\n” 编译器引发的错误为:

    error: no matching function for call to 'std::__cxx11::basic_string<char>::replace(std::__cxx11::string&, const size_type&, std::__cxx11::string&)'
错误:调用“std::u cxx11::basic_string::replace(std:uu cxx11::string&,const size_type&,std:u cxx11::string&)”时没有匹配的函数
你能回答工作代码并解释为什么你会这样做吗

我在这里学习了string::replace()方法:

我使用string::find()作为替换字符串的起点的逻辑是否正确

我使用string::find()作为替换字符串的起点的逻辑是否正确

是的,但随后您放弃了
find
的迭代器/索引结果,转而获取子字符串

替换不需要字符串

它需要一个迭代器/索引

因此,只需将从
find
获得的内容传递到
replace
。(小心边缘情况!检查错误!阅读两个函数的文档。)

#包括
#包括
#包括
使用名称空间std;
int main()
{
fstream subor(“test.txt”);
弦线;
while(getline(subor,line))
{
//在第一个“?”之后查找字符的索引
const size\u t wantedStringPos=line.find(“?”)+1;
//提示输入替换字符串

您想调用的
string::replace
重载是什么?您传递的参数没有重载…因此我将“string wantedString”更改为“int wantedString=line.find(“?”)+1”,添加了“string replace=line.replace”(wantedString,string::npos,newString)'并尝试使用更新文件'subor@IvoJOKERDurec您仍在向
replace
传递字符串。您应该阅读文档以了解如何使用
replace
。要获得格式帮助,请单击“帮助”注释框旁边的链接;它会教你如何使其可读。我不明白…我应该传递什么?在我发布的链接上写着第三个参数是字符串,或者我缺少什么?@IvoJOKERDurec,那么第一个参数呢?第一个参数是“另一个字符串对象,其值被复制。”from和我尝试将字符串更改为wantedString的大小,但这也不起作用。。。
    error: no matching function for call to 'std::__cxx11::basic_string<char>::replace(std::__cxx11::string&, const size_type&, std::__cxx11::string&)'
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    fstream subor("test.txt");

    string line;
    while (getline(subor,line))
    {
        // Find the index of the character after the first '?'
        const size_t wantedStringPos = line.find("?")+1;

        // Prompt for a replacement string
        cout << "Enter new text to replace wantedString: ";
        string newString;
        getline(cin,newString);

        // Perform the replacement
        line.replace(wantedStringPos, string::npos, newString);

        // Now do something with `line`
        // [TODO]
    }
}