gpt4 book ai didi

c++ - 格式化读取文件数据C++

转载 作者:行者123 更新时间:2023-11-28 03:42:50 25 4
gpt4 key购买 nike

我在文件中有以下格式的数据( p1, p2 ) (p3, p4 ) ( p5, p6 )

我如何在 C++ 中读取它,我可以读取一行并解析它,但我正在寻找一些 C++ STL 方法来读取这种格式。

最佳答案

这取决于您希望在程序中表示数据的格式。一种方法是使用 struct使用自定义流提取运算符:

struct Data {
int val1; // just assuming int for the data-type
int val2;
};

std::istream & operator>>(std::istream& input, Data & obj) {
input.ignore(2, '('); // skip all including opening brace
input >> obj.val1;
input.ignore(2, ','); // skip comma
input >> obj.val2;
input.ignore(2, ')'); // skip closing brace
return input;
}

正如@Seth Carnegie 在 answer to a similar question 中展示的那样, 你也可以使用 INT_MAX确保你跳过足够多 - 但是,使用 std::numeric_limits<std::streamsize>::max()会更好。

然后你可以像这样读取文件的所有内容:

std::vector<Data> all_data;
std::ifstream input_file("your_file.txt");
std::copy(std::istream_iterator<Data>(input_file),
std::istream_iterator<Data>(),
std::back_inserter(all_data));

Here是一个完整的工作示例。

关于c++ - 格式化读取文件数据C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572441/

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