C++在不使用字符串流的情况下读取具有任意长度和格式的行的多行文件

标签 c++ stream inputstream

我有一个包含以下行的输入流:

# <int> <int>
<some_data_type> <some_data_type> <some_data_type> ..... <some_data_type>
<some_data_type_1> <some_data_type_2> <some_data_type_3> <some_data_type_1> <some_data_type_2> <some_data_type_3> .... <some_data_type_1> <some_data_type_2> <some_data_type_3> 

在上面的流中,所有三行都是不同的,必须以不同的方式解析。目前,我使用的阅读方法如下:

void reader( std::istream & is, DataStructure & d ){
  std::string line;
  getline(is,line);
  std::stringstream s(line);
  //parse line 1

  getline(is,line);
  std::stringstream line2(line);
  //parse line 2

  getline(is,line);
  std::stringstream line3(line);
  //parse line 3

 }

现在的想法是根本不使用 std::stringstream,因为一行可以任意大,我们不想将所有内容加载到内存中两次。因此,如果可以从输入流直接读取到用户给定的数据结构 d 中会更好。

一个想法是利用 std::istream_iterator 但不幸的是不同的行有不同的解析需求。例如,在最后一行中,流中的三个元素共同构成了一个数据元素。

目前对我来说唯一合理的想法是直接处理流缓冲区。如果有人能推荐一种更好的方法来做这件事,那就太好了。

注意:不能使用像std::stringstream这样的三级数据结构。必须从流中直接读取到用户提供的数据结构中。

编辑:请注意我们只允许一次通过文件。

最佳答案

Now the idea is not to make use of std::stringstream at all, as a line can arbitarily large and we donot want to load everything into memory twice. So, it would be better if it was possible to read from the input stream directly into the user given datastructure d.

Olaf 解释了上面的提取运算符,但我们有一个新要求:

This will only work for the first line, where it is known there is a fixed number of elements.

(2) Unfortunately, I have no discriminator beyond my knowledge that each instance of the data structure needs to be instantiated with information stored in three different lines. All three lines have different lengths and different data elements. Also, I cannot change the format.

加上

(3) All information is treated as unsigned integer.

现在的下一个问题是我们不知道数据结构到底是什么,所以考虑到之前发生的事情,它似乎以某种方式是动态的。因为我们可以将数据视为无符号整数,所以我们可以使用提取运算符,但读入动态成员:

vector<unsigned int> myUInts;
...
inFile >> currentUInt;
myUInts.push_back(currentUInt);

但随后就出现了在哪里停止的问题。是在第一行的末尾,第三行吗?如果您需要读取任意数量的无符号整数,同时仍然检查新行,那么您还需要处理空白:

inFile.unsetf(ios_base::skipws);

如果没有更明确的要求,您实际如何处理这超出了我目前可以说的范围。但我想它将采用以下形式:

 inFile >> myMember;
 char next = infile.peek()
 //skip whitespace and check for new line
 //Repeat until data structure filled, and repeat for each data structure.

关于C++在不使用字符串流的情况下读取具有任意长度和格式的行的多行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13510453/

相关文章:

stream - 树莓派 : cvlc "Floating point exception"

java - 将文件作为输入流读取时如何获取 Excel 文件名

c++ - 在 C++ 中声明二维指针数组的方法

c++ - 实现字符串的 C++ 运算符

c# - 为什么使用 StreamWriter 将文本写入字符串导致未写入任何内容?

java - 在java中,如何从输入流中读取固定长度并保存为文件?

java - Java 中的自动文件/输入流处理

c++ - make_shared 与自定义新运算符

java - 当任何匹配值时返回匹配枚举