如何在文本文件c+中查找和替换一行数据+; 我试图在C++中找到并替换文本文件中的一行数据。但我真的不知道从哪里开始
我在考虑使用 open(“test.txt”,ios::in | ios::out | ios|u base::beg | ios::app) 在开头打开文件并附加到其上,但这不起作用 有人知道实现这项任务的方法吗 谢谢如何在文本文件c+中查找和替换一行数据+; 我试图在C++中找到并替换文本文件中的一行数据。但我真的不知道从哪里开始,c++,file,text,io,C++,File,Text,Io,我在考虑使用 open(“test.txt”,ios::in | ios::out | ios|u base::beg | ios::app) 在开头打开文件并附加到其上,但这不起作用 有人知道实现这项任务的方法吗 谢谢 编辑:我的文本文件只有一行,它包含一个数字,例如504。然后,用户指定一个要减去的数字,然后该数字的结果将替换文本文件中的原始数字。是的,您可以使用std::fstream执行此操作,下面是我快速创建的一个快速实现。打开文件,迭代文件中的每一行,并替换出现的任何子字符串。替换子
编辑:我的文本文件只有一行,它包含一个数字,例如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::fstream文件(“test.txt”,std::ios::in);
if(file.is_open()){
std::string replace=“bar”;
std::string将_替换为=“foo”;
std::字符串行;
std::矢量线;
while(std::getline(文件,行)){
std::cout您可以使用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;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
std::ifstream ifs(“test.txt”);
std::字符串行;
int num,其他_num;
if(std::getline(ifs,line))
{
std::stringstream-ss;
ss>num;
}
其他的
{
为了帮助您,您可以复制不适合您的代码吗?如果文件不太大,您可以使用std::getline()
读入行,将要保留的行添加到向量
,跳过不想保留的行。然后将该向量
写入一个文件。虽然通常,对于此类任务,我会使用类似sed
@Adam27X的东西。我的文本文件只有一行,并且包含一个数字,例如504。下面的然后,用户指定一个要减去的数字,然后减去的结果将替换文本文件中的原始数字。不过,我很困惑。如果文本文件是一行,其中包含一个数字,则此处不涉及查找/替换。这是一个简单的读/写操作。从文件中读取值,返回到开头,然后写入新的值文件的值。老实说@Ken White我在找的是查找和替换数字。相反,我用一个简单的读/写操作替换了这段代码,效果很好。非常感谢!这确实帮助我理解了在文件中查找和替换,因为我以前从未接触过向量。谢谢