简体   繁体   English

getline 行尾?

[英]getline end of line?

I have an text file with binary values in n columns and y rows.我有一个包含 n 列和 y 行二进制值的文本文件。

I am using getline to extract every row of the binary values and assign them to vectors: 我正在使用 getline 提取二进制值的每一行并将它们分配给向量:
I am using getline to extract every row of a file, where each row consists of a series of '0' or '1' separated by space, and assign them to a vector.我正在使用 getline 提取文件的每一行,其中每一行由一系列用空格分隔的“0”或“1”组成,并将它们分配给一个向量。

std::vector< std::vector<int> > matrix; // to hold everything.
std::string line;
while(std::getline(file,line))
{
  std::stringstream linestream(line);
  int  a,b,c,d;
  linestream >> a >> sep >> b >> sep >> c >> sep >> d;
  std::vector <int> vi;
  vi.push_back(a);
  vi.push_back(b);
  vi.push_back(c);
  vi.push_back(d);
  matrix.push_back(vi);
}

Now the problem is that I do not know in advance how many columns are there in the file.现在的问题是我事先不知道文件中有多少列。 How can I loop through every line until i reach the end of that line?如何循环遍历每一行,直到到达该行的末尾?

The obvious way would be something like:显而易见的方法是:

while (linestream >> temp >> sep) 
    vi.push_back(temp);

Though this may well fail for the last item, which may not be followed by a separator.尽管最后一项可能会失败,但后面可能没有分隔符。 You have a couple of choices to handle that properly.你有几个选择来正确处理这个问题。 One would be the typical "loop and a half" idiom.一种是典型的“循环半”成语。 Another would be a locale that treats your separator characters as white space.另一个是将分隔符视为空格的语言环境

When/if you do that, you can/could also use a standard algorithm:当/如果你这样做,你可以/也可以使用标准算法:

std::copy(std::istream_iterator<int>(linestream),
          std::istream_iterator<int>(),
          std::back_inserter(vi));

Why not while (in1 >> i) row.push_back( i );为什么不 while (in1 >> i) row.push_back( i ); Which does not require a separator?哪个不需要分隔符?

check for a new line character (\n).检查换行符 (\n)。 when you find one, you've completed the line/column.当你找到一个时,你已经完成了行/列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM