c++ - 从文件中读取和写入 int 对

标签 c++ file input stream output

我正在尝试从文件中读取和写入一系列 int 对。该文件看起来像这样:

0 6
12 24
48 33
23 24
80 79

我的目标是将每一对读入一个结构:

struct foo {
    int a;
    int b;
}

然后将每个结构压入堆栈。然而,事实证明,fstreams 很难处理此任务。现在,我的文件读取代码如下所示:

std::fstream fileStream(file, std::ios::in);
int a, b;
while (fileStream >> a >> b) {
    myStack.push({ a, b });
}

我的输入可能看起来像这样(我必须单独输入,因为我正在使用它......):

inputFoo(foo bar) {
    std::fstream fileStream(file, std::ios::out);
    fileStream << bar.a << " " << bar.b;
}

但是,我觉得这不是我应该高效、安全地执行此操作的方式。我还有一个检查文件是否已经存在的函数,但我不确定它是否有效:

bool fileExists() {
    std::ifstream stream;
    return stream.good();
}

实际执行此操作的最佳方法是什么?

最佳答案

这样做

std::ifstream fileStream(file, std::ios::in);

while (!fileStream.eof()) {
    foo f;
    fileStream >> f.a>> f.b
    myStack.push(f);
}

循环将读取整个文件结束

写起来会这样

std::ofstream fileStream(file, std::ios::in);

while (!myStack.isEmpty()) {
    foo f;
    f=myStack.pop();
    fileStream << f.a<<" "<< f.b<<endl;

}

关于c++ - 从文件中读取和写入 int 对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006875/

相关文章:

android - 如何使用 Android 应用程序编写文件?

jquery - 当文本太长时,在文本框中使用 jQuery 模拟 "typing text"

c - 如何从 c 中的文本文件创建多个运行总计的函数?

javascript - 什么是好的 Javascript 时间选择器?

Javascript - 如何在不清除输入的情况下更改标签的 innerText

c++ - QTableWidget 显示滚动条

c++ - 三角形之间的相似性;双变量是一个痛苦的

c++ - 使用模板折叠表达式而不是函数模板的递归实例?

c++ - Symbian C++ - 删除或隐藏组件(即 CEikLabel)

c# - 从流阅读器中删除最后 x 行