我想在文件中找到一个字符串并将其替换为用户输入。
这是我粗略的代码。在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`?
}
}
}
UPDATE
这里是解决我的问题代码
的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。在那之后,用户输入名字和姓氏Shafiq
和Ahmed
。 乳宁这个代码test.txt
文件必须修改记录一样,后:
…
id_2
Shafiq
Ahmad
…
只有记录更改,剩下的文件将保持不变。
建议:写入一个新文件并将其移动到原始文件+ std :: string中查找并替换成员函数。 – stefaanv
我刚才看到你想要替换完整的行,所以只有我的第一个建议是有效的。第二个是取代部分线条。文件中的内联替换仅适用于替换相同的大小。 – stefaanv