开发者

getline end of line?

开发者 https://www.devze.com 2023-03-16 12:36 出处:网络
I have an text file with binary values in n columns and y rows. I am using getline 开发者_开发知识库to extract every row of the binary values and assign them to vectors:

I have an text file with binary values in n columns and y rows.

I am using getline 开发者_开发知识库to extract every row of the binary values and assign them to vectors:

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.

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 ); Which does not require a separator?


check for a new line character (\n). when you find one, you've completed the line/column.

0

精彩评论

暂无评论...
验证码 换一张
取 消