gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:24:06 27 4
gpt4 key购买 nike

我正在尝试从文件中读取和写入一系列 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/

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