【发布时间】:2014-02-06 11:01:49
【问题描述】:
我想在文件中查找一个字符串并将其替换为用户输入。
这是我的粗略代码。
#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`?
}
}
}
更新
这是解决我问题的代码
test.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 记录发生变化,其余文件将保持不变。
【问题讨论】:
-
建议:写入一个新文件并将其移到原始文件上 + std::string 具有查找和替换成员函数。
-
我刚刚看到你想替换完整的行,所以只有我的第一个建议是有效的。二是更换部分线路。文件中的内联替换仅适用于相同大小的替换。