查找并删除文件 C++ 中的整行
find and delete whole line in file c++
我有一个文件,内容用';"分隔,像这样
JACK;Basketball;Afternoon
JACK;Football;Morning
JOE;Basketball;Morning
JIM;Football;Morning
KEN;Gym;Morning
MARK;Gym;Morning
所以我有这个代码
void deleteCourseData(string courserName, string courserType, string courseTime) {
ifstream myfile;
myfile.open("file.csv");
ofstream temp;
temp.open("temp.txt");
string line;
while (getline(myfile, line))
{
if(line.substr(0, courserName.size()) != courserName)
temp << line << endl;
}
myfile.close();
temp.close();
remove("file.csv");
rename("temp.txt", "file.csv");
}
此代码搜索课程名称并删除所有具有相同名称的数据。
因此,我想搜索所有数据"courserName,courserType,courseTime",然后删除该数据的整行。
您可以简单地将三个参数连接成一个字符串,并检查它,例如:
void deleteCourseData(string courserName, string courserType, string courseTime)
{
// additional scope introduced to control the lifetime of myfile and temp
{
ifstream myfile("file.csv");
ofstream temp("temp.txt");
string line;
string targetLine = courserName + ";" + courserType + ";" + courseTime;
while (getline(myfile, line))
{
if (line != targetLine)
temp << line << endl;
}
}
remove("file.csv");
rename("temp.txt", "file.csv");
}
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 如何从存储在std::映射中的std::集中删除元素
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数