在c中搜索和替换txt文件中的字符串

新手上路,请多包涵

我想在文件中找到一个字符串并将其替换为用户输入。

这是我的粗略代码。

 #include <iostream>
#include <fstream.h>
#include <string.h>

int main(){
    istream readFile("test.txt");

    string readout,
         search,
         replace;

    while(getline(readFile,readout)){
        if(readout == search){
            // How do I replace `readout` with `replace`?
        }
    }
}

更新

这是解决我问题的代码

测试.txt:

 id_1
arfan
haider

id_2
saleem
haider

id_3
someone
otherone

C++ 代码:

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

using namesapce std;

int main(){
    istream readFile("test.txt");
    string readout,
           search,
           firstname,
           lastname;

    cout << "Enter the id which you want to modify";
    cin >> search;

    while(getline(readFile,readout)){
        if(readout == search){
            /*
                id remains the same
                But the First name and Last name are replaced with
                the user `firstname` and `lastname` input
            */
            cout << "Enter new First name";
            cin >> firstname;

            cout << "Enter Last name";
            cin >> lastname;
        }
    }
}

认为:

用户搜索 id id_2 。在该用户之后输入名字和姓氏 ShafiqAhmed 。运行此代码后, test.txt 文件必须像这样修改记录:

 …

id_2
Shafiq
Ahmad

…

只有 id_2 记录更改,其余文件将保持不变。

原文由 Axeem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 344
1 个回答

你可能打算写:

 tmp.replace(tmp.find(oldw), oldw.length(), neww);

使其正常工作。 sizeof() 很可能总是返回 4。

原文由 user2861563 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题