gpt4 book ai didi

c++ - 使用 std::get_temporary_buffer 从文件中读取数据

转载 作者:行者123 更新时间:2023-11-28 04:10:42 32 4
gpt4 key购买 nike

我有这个结构

struct myStruct {
int i,j;
double x,y,z,f;
myStruct(int i_, int j_, double x_, double y_, double z_, double f_):
i(i_),j(j_),x(x_),y(y_),z(z_),f(f_){}
}
};

我想从文本文件(有 5 列)中读取数据并将它们放入结构 vector myStruct 中。我想将读取的文本文件和插入到 vector 中的内容分开。为了阅读,我必须在内存中使用一个临时缓冲区,我可以使用 get_temporary_buffer 吗?我该怎么做?

最佳答案

std::get_temporary_buffer 在 C++17 中被弃用,并且(很可能)将在 C++20 中被删除,所以我不会在任何新程序中使用它,但你可以轻松添加您自己的格式化流媒体运营商。

#include <ios>
#include <iostream>
#include <sstream>
#include <string>

struct myStruct {
int i, j;
double x, y, z, f;

myStruct(int i_, int j_, double x_, double y_, double z_, double f_) :
i(i_), j(j_), x(x_), y(y_), z(z_), f(f_) {}

myStruct() : // default constructor
myStruct(0, 0, 0., 0., 0., 0.) // delegating
{}

/* if you make your member variables private, you'll need to make the
* streaming functions friends, like this:
friend std::istream& operator>>(std::istream&, myStruct&);
friend std::ostream& operator<<(std::ostream&, const myStruct&);
*/
};

std::istream& operator>>(std::istream& is, myStruct& m) {
std::string line;
// read one line from the stream
if(std::getline(is, line)) {
// put the line in an istringstream for extracting values
std::istringstream ss(line);
if(!(ss >> m.i >> m.j >> m.x >> m.y >> m.z >> m.f)) {
// if extraction failed, set the failbit on the stream
is.setstate(std::ios::failbit);
}
}
return is;
}

std::ostream& operator<<(std::ostream& os, const myStruct& m) {
return os << m.i << ' ' << m.j << ' ' << m.x << ' ' << m.y << ' ' << m.z << ' '
<< m.f << "\n";
}

int main() {
// using a simulated file (a_file) opened for reading:
std::istringstream a_file(
"1 2 3.1 4.2 5.3 6.4\n"
"2 3 4.1 5.2 6.3 7.4\n"
"3 4 5.1 6.2\n"); // the last line will fail to be extracted since it
// contains too few values

myStruct tmp;
// Read until eofbit, failbit or badbit is set on the stream.
// The stream object will be "true" in a boolean context (like the
// while(<condition>)) if it's in a good state.
while(a_file >> tmp) {
// the stream "a_file" is in a good state so extraction succeeded
std::cout << tmp;
}
std::cout << "goodbye\n";
}

关于c++ - 使用 std::get_temporary_buffer 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57854951/

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