如何在文本文件C ++中查找和替换一行数据 [英] How can I find and replace a line of data in a text file c++
问题描述
我试图在c ++中的文本文件中查找并替换一行数据.但老实说,我不知道从哪里开始.
I am trying to find and replace a line of data in a text file in c++. But I honestly have no idea where to start.
我正在考虑使用 replaceNumber.open("test.txt",ios :: in | ios :: out | ios_base :: beg | ios :: app);
I was thinking of using replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);
要从头开始打开文件并追加到文件上,但这是行不通的.
To open the file at the beginning and append over it but this doesn't work.
有人知道实现此任务的方法吗?
Does anyone know of a way to achieve this task?
谢谢
我的文本文件只有一行,并且包含一个数字,例如504.然后,用户指定一个要减去的数字,然后结果应替换文本文件中的原始数字.
My text file is only one line and it contains a number for example 504. The user then specifies a number to subtract then the result of that should replace the original number in the text file.
推荐答案
是的,您可以使用std :: fstream做到这一点,这是一个快速的实现,我很快就提出了.您打开文件,遍历文件中的每一行,并替换子字符串的所有出现.替换子字符串后,将行存储到字符串向量中,关闭文件,用std::ios::trunc
重新打开,然后将每一行写回到空文件中.
Yes, you can do this using std::fstream, here's a quick implementation i whipped up real quick. You open the file, iterate over each line in the file, and replace any occurrences of your substring. After replacing the substring, store the line into a vector of strings, close the file, reopen it with std::ios::trunc
, and write each line back to the empty file.
std::fstream file("test.txt", std::ios::in);
if(file.is_open()) {
std::string replace = "bar";
std::string replace_with = "foo";
std::string line;
std::vector<std::string> lines;
while(std::getline(file, line)) {
std::cout << line << std::endl;
std::string::size_type pos = 0;
while ((pos = line.find(replace, pos)) != std::string::npos){
line.replace(pos, line.size(), replace_with);
pos += replace_with.size();
}
lines.push_back(line);
}
file.close();
file.open("test.txt", std::ios::out | std::ios::trunc);
for(const auto& i : lines) {
file << i << std::endl;
}
}
这篇关于如何在文本文件C ++中查找和替换一行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!