0

I have a file containing the following lines:

5556
0   bla.dxf
1   blub.dxf
2   buzz.dxf

The numbers and text are seperated by a singular tab each, there is no whitespace character after 5556. The following code is used for parsing.

int main(int, char**){
  std::ifstream file("test.bld");
  std::string buildingName;
  file >> buildingName;
  std::cout << buildingName << std::endl;
  std::string buf;
  while(getline(file, buf)) {
    if(buf.empty()){std::cout << "String was empty"<<std::endl;}
    else std::cout << buf << std::endl;
  }
  return 0;
}

When I parse the file I get an empty line although there obviously is none. The output reads as follows:

5556
String was empty
0   bla.dxf
1   blub.dxf
2   buzz.dxf

This is only a minimal example. The whole file and the parser is more complex and I would very much like to use direct parsing for the first element and getline for the rest. What am I misunderstanding about line parsing with getline and how do I avoid getting empty lines?

Martin
  • 4,738
  • 4
  • 28
  • 57
  • 2
    `operator >>` leaves the new line character in the input buffer - see [this answer](http://stackoverflow.com/a/10842558/1374437). – Hristo Iliev Jul 09 '12 at 13:04
  • Just found the following which explains my mistake: http://stackoverflow.com/a/7787253/484230. The quintessence is: don't mix or you're in for trouble – Martin Jul 09 '12 at 13:06

2 Answers2

5

operator>>(istream, string) reads up to but not including the first whitespace character after the extracted token.

To skip the rest of the line after extracting a token, you can either use

std::cin >> std::ws;

(if you know that there is only a newline remaining), or

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

to skip to the end of the line regardless.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
4

I'm assuming because

file >> buildingName;

doesn't move the cursor to the next line, but leaves it at the end of the current line. So when you call getline, you'll read an empty string and then move to the next.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • That explains things. When is a cursor moved to the next line ? When I have pure stream input this is not a problem in >> a >> b >> c skips also line feeds. But with a dynamic combination of getline() .. in>> a ... getline, when is the linefeed read – Martin Jul 09 '12 at 13:03
  • 1
    @Martin This is just an assumption (which probably is correct). The thing is I don't know for sure since I never combine the two types of reading. I either use `>>` or `getline`. – Luchian Grigore Jul 09 '12 at 13:04
  • The assumption is correct. `>>` reads the string up to but not including any whitespace (the whitespace is skipped on the next call). – David Rodríguez - dribeas Jul 09 '12 at 13:20