如何在C ++中替换文本文件中的单词? [英] How Do I Replace A Word In A Text File In C++?
本文介绍了如何在C ++中替换文本文件中的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在文本文件中找到替换它的单词。现在,我可以在文本文件中找到成功的单词,但我无法替换它。任何人都可以建议我在哪里犯了错误。谢谢。
I am trying to find a word an replace it in the text file. Now, i can find the word successfully in the text file but i am unable to replace it. Can anyone please suggest me where i made the mistake. Thanks.
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
int main(){
ifstream input;
ofstream output;
output.open("Book1.txt",ios::app);
int choice;
size_t pos;
size_t p;
string line;
string a;
string id;
cout<<"enter the name you want to search"<<endl;
cin>>a;
string replace = "hello";
size_t len = a.length();
input.open("Book1.txt",ios::out);
if(input.is_open())
{
while(getline(input,line))
{
pos = line.find(a);
if(pos!=string::npos)
{
line.replace(pos,len,replace);
cout<<"Name://IDnumber//Account-Balance"<<" "<<line<<endl;
}
}
}
system("pause");
}
推荐答案
读取字符串中的整个文件并使用replace 。
检查所有字符串是否已被替换,而不是写新的字符串到文件
read the whole file in a string and use replace.
Check that all strings are replaced and than write the new string to the file
这篇关于如何在C ++中替换文本文件中的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文