我想在文件中找到一个字符串并将其替换为用户输入。
这是我的粗略代码。
#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
。在该用户之后输入名字和姓氏 Shafiq
和 Ahmed
。运行此代码后, test.txt
文件必须像这样修改记录:
…
id_2
Shafiq
Ahmad
…
只有 id_2
记录更改,其余文件将保持不变。
原文由 Axeem 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可能打算写:
使其正常工作。
sizeof()
很可能总是返回 4。