0

I'm working on a very simple parser for wavefront *.obj files.

The general idea is to read each line of the file and then based on the start keyword parse that line accordingly, but I have some troubles with it:

bool Model::loadModel(const char* fileName)
{
 std::ifstream file(fileName, std::ios::binary);

 if(file.fail())
  return false;

 std::string line;
 std::string type;
 std::istringstream istr;

 while(std::getline(file, line))
 {
  istr.str(line); 
  istr>>type;

.
.
.

For example the file I have has in its first line:

g Dragon

so in "type" I have a "g" stored. The problem is that when I read the next line

v -0.136296 0.0938588 -0.0307373

istr is apparently initialized but after the >> operation type still has "g".

The loop continues and that "g" value never changes.

I have some other *.obj files that I can read perfectly, the only difference is that in the debuger I see a '\r' at the end of all the lines.

Is this character needed to extract data from a istringstream?

user1274605
  • 405
  • 2
  • 6
  • 17
  • 1
    Did you try putting the istr declaration inside the while loop, not outside? – Marius Bancila Jul 24 '13 at 20:28
  • Did you try the first question in the sidebar "Related"? [C++ - repeatedly using `istringstream`](http://stackoverflow.com/questions/2767298/c-repeatedly-using-istringstream?rq=1) --> use `istr.reset()` after `istr.str(..)`. – dyp Jul 24 '13 at 20:48
  • @Marius Bancila thanks for you answer, it worked!! though I don´t know why it failed in the first place. ?? – user1274605 Jul 24 '13 at 20:56
  • @DyP mmm... you mean clear() function right? that worked too!! – user1274605 Jul 24 '13 at 20:59
  • 1
    @user1274605 I guess what happened is: Some of your files had Windows-style line endings (`"\r\n"`). `getline` reads until `'\n'`, therefore includes the `'\r'` which becomes the last character in `istr`. When you now extract things out of `istr`, the `\r` stays. If there's no `'\r'` at the end of a line, at some point your extraction reaches the end of `istr`, then the `eof`-bit of `istr` is set. After this, any further extraction from `istr` fails. By calling `istr.clear()`, the `eof` bit is cleared. `istr.str(..)` does **not** clear the `eof`-bit. – dyp Jul 24 '13 at 21:06
  • @user1274605 Oops, yeah I meant `.clear()` :) – dyp Jul 24 '13 at 21:09

0 Answers0