简体   繁体   中英

getline end of line?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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