gpt4 book ai didi

c++ - ifstream 和 ofstream : How do I perform multiple modifications to a file?

转载 作者:行者123 更新时间:2023-11-28 05:17:46 25 4
gpt4 key购买 nike

我已经用谷歌搜索这个问题几个小时了,但似乎找不到任何可以解决的问题。

我对 C++ 中的文件操作一窍不通,但在过去的 36 个小时中,我花了大约 20 个小时阅读文档和论坛问题,试图为 friend 一起完成一个项目。

假设我有一个名为 raw_questions.txt 的文件,我想对其进行一些更改。该文件是考试的学习指南,包含一个问题和 4 个多项选择答案。我想删除空行并添加一些标记以允许我正在处理的另一个程序解析它。我已经编写了一个格式化程序来执行这些操作。这些操作是:

  1. 从源文件中删除双倍行距的空行
  2. 在每个问题的末尾添加一个分隔符 ('@') 并回答。
  3. 使用分隔符,将每个问题和答案作为一个字符串读出并将其附加到输出文件中,并在问题或答案,这将使我的其他程序知道是否行包含问题或答案。

我的问题:我被困在如何从一个操作转移到下一个操作上。我目前的做法是将每一行读入一个字符串,对字符串执行操作,然后将新字符串添加到输出文件中。使用这种方法,要执行下一个操作,我必须打开前一个操作的输出文件作为我的新输入文件,并为该操作创建一个新的输出文件。我觉得必须有更好的方法,但就像我说的,我对 C++ 中的文件操作很不了解。在这种情况下我应该怎么做?

我考虑过创建一个 ifstream 和 ofstream,它们都指向同一个文件,并希望当 ifstream 文件打开时,它将在内存中存储一​​个临时拷贝。然后,在我逐行读取并写入我的 ofstream 对象后,当它关闭时它将覆盖我的旧文件。我不知道这是否有意义,我什至不认为 fstream 是这样工作的。

我目前的代码:

#include <fstream>
#include <string>
#include "Debug.h"

Debug debugger;

void remove_empty_lines (std::ifstream& input, std::ofstream& output);
void insert_delimiter (std::ifstream& input, std::ofstream& output, char delimiter);
void create_output (std::ifstream& input, std::ofstream& output);

int main() {
debugger.set_active();

char delimiter = '@';

std::ifstream input;
std::ofstream output;
input.open("questions_source.txt");
output.open("questions_intermidiate.txt");

remove_empty_lines (input, output);

}

void remove_empty_lines (std::ifstream& input, std::ofstream& output) {
while (!input.eof()) {
std::string line;

std::getline(input, line);
if (line != "") {
output << line << std::endl;
}
}
}

void insert_delimiter(std::ifstream& input, std::ofstream& output) {
}

// This function doesn't quite work, WIP - Please ignore
void create_output(std::ifstream& input, std::ofstream& output) {
std::string line;

for (int i = 1; !input.eof(); i++) {
debugger.out("Inserting tokens.");
bool found = false;
while (!found) {
getline (input, line);
if (i < 10) {
if (line[1] == ')') {
line.erase (0, 3);
output << "[" << i << "]" << line << std::endl;
debugger.out("Found line: " + line);
found = true;
}
} else if (i < 100) {
if (line[2] == ')') {
line.erase (0, 4);
output << "[" << i << "]" << line << std::endl;
debugger.out("Found line: " + line);
found = true;
}
}
}

for (int j = 0; j < 4; j++) {
getline (input, line);
if (line[1] == ')') {
line.erase (0, 3);
output << "[" << i << "a]" << line << std::endl;
}
}

}
}

我现在也在尝试自学 git,所以我正在做的项目正好托管在 github 上 here .我不知道上下文是否会让我想做的事情变得有意义,但我发布它以防万一。

奖金问题:我一直在绞尽脑汁,但我还没有想出添加分隔符的解决方案。答案似乎只有一行,所以我可能只需将定界符添加到以“A)”等开头的任何行的末尾,但有些问题要长得多。我的想法是找到任何出现的“A)”并将定界符添加到它上面一行的末尾,但我想不出该怎么做。任何人都可以为 fstream 的成员函数指出正确的方向吗?

感谢阅读。

最佳答案

流不会神奇地将整个文件读入内存。如果那是你想做的,你应该这样做:我的猜测是你的文件比你的可用内存小得多,使用标准 C++ 容器执行所有操作可能更容易。

关于c++ - ifstream 和 ofstream : How do I perform multiple modifications to a file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42254691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com