如何在文本文件 c++ 中查找和替换一行数据
How can I find and replace a line of data in a text file c++
我正在尝试在 c++ 的文本文件中查找和替换一行数据。但老实说,我不知道从哪里开始。
我正在考虑使用 replaceNumber.open("test.txt", ios::in | ios::out | ios_base::beg | ios::app);
在开头打开文件并附加在它上面,但这不起作用。
有谁知道完成这项任务的方法?
谢谢
编辑:我的文本文件只有一行,它包含一个数字,例如504。然后,用户指定一个数字来减去,然后其结果应替换文本文件中的原始数字。
是的,你可以使用 std::fstream 来做到这一点,这是一个示例实现。打开文件,循环访问文件中的每一行,并替换子字符串的任何匹配项。替换子字符串后,将行存储到字符串向量中,关闭文件,使用 std::ios::trunc
重新打开它,然后将每一行写回空文件。
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;
}
}
可以使用
std::stringstream
将从文件中读取的字符串转换为整数,并将std::ofstream
与std::ofstream::trunc
一起使用以覆盖文件。
#include <iostream>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <sstream>
int main()
{
std::ifstream ifs("test.txt");
std::string line;
int num, other_num;
if(std::getline(ifs,line))
{
std::stringstream ss;
ss << line;
ss >> num;
}
else
{
std::cerr << "Error reading line from file" << std::endl;
return 1;
}
std::cout << "Enter a number to subtract from " << num << std::endl;
std::cin >> other_num;
int diff = num-other_num;
ifs.close();
//std::ofstream::trunc tells the OS to overwrite the file
std::ofstream ofs("test.txt",std::ofstream::trunc);
ofs << diff << std::endl;
ofs.close();
return 0;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 用现代C++STL数据结构替换旧的C风格数组
- 调用Main将替换矢量对象并覆盖数据
- 将数据从 JavaScript 发送到 C++,超过 127 的字节值将替换为 "replacement character"
- 如何在不重写整个视频文件的情况下仅替换流中的一个数据框架?(ffmpeg)
- 使用Hazelcast替换共享内存结构数据
- 为什么数据中的随机部分替换了曾经存储在我的角色数组中的其他数据
- 如何用堆栈数据结构替换递归功能调用
- 分析位图文件时,如何替换WORD和DWORD数据类型
- 在浏览器中呈现数据之前,是否可以拦截http请求并修改数据(例如使用regex替换内容)?如果是,如何
- 替换文本文件而不是推送数据
- 替换2D矢量C++中的数据
- 外部存储器数据结构,以替换地图的矢量
- 如何在文本文件 c++ 中查找和替换一行数据
- 如何替换链表中某个节点的数据
- 如何替换WSAStartup(MAKEWORD(2,2),和数据);与助推器:ASIO?
- 如何用字符串中的数据替换访问说明符
- 我如何替换std::vector的某些范围的数据
- 将容器的内容替换为其他容器中的数据
- C 气泡排序:排序数组丢失最大的数据片段,并替换为内存地址