0

I am trying to parse a file. I am currently using the following code, but would like to replace it with a sstream based solution

unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
const char* cstring = line.c_str();
int matches = sscanf(cstring, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);

When I try the following, I get unexpected results

std::stringstream f(line);
f >> vertexIndex[0] >> uvIndex[0] >> normalIndex[0] >> vertexIndex[1] >> uvIndex[1] >> normalIndex[1] >> vertexIndex[2] >> uvIndex[2] >> normalIndex[2];

I am sure I am misunderstanding the stream use somehow... any help would be awesome!

  • 1
    Where do you account for the "f", and for the slashes? I don't see that you've written any code to do that. – Lightness Races in Orbit Aug 10 '16 at 13:07
  • 1
    (To be quite honest, even in C++, your original solution is probably preferable in most cases.) – Lightness Races in Orbit Aug 10 '16 at 13:09
  • Possible duplicate of [Reading in a specific format with cin](http://stackoverflow.com/questions/14901678/reading-in-a-specific-format-with-cin) – Ami Tavory Aug 10 '16 at 13:15
  • Note that while [Reading in a specific format with cin](http://stackoverflow.com/questions/14901678/reading-in-a-specific-format-with-cin) discusses `cin` rather than an `stringstream`, the main point - dealing with the specific-form literals - is the same in both questions. – Ami Tavory Aug 10 '16 at 13:16
  • Thank you all. It was mostly my misunderstanding of the stringstream >> operator. The "account for slashes" is what made it click. std::stringstream ss(line.substr(2)); char throwaway; for (int i = 0; i < 3; i++){ ss >> vertexIndex[i] >> throwaway >> uvIndex[i] >> throwaway >> normalIndex[i]; } – Mickey Macdonald Aug 10 '16 at 15:13

1 Answers1

0

It was a simple lack of understanding. The solution to my particular issue was:

std::stringstream ss(line.substr(2)); 
char throwaway; 
for (int i = 0; i < 3; i++){ 
     ss >> vertexIndex[i] >> throwaway >> uvIndex[i] >> throwaway >> normalIndex[i]; 
}

My next question is why the following does not work?

ss.ignore(std::numeric_limits<std::streamsize>::max(), '/');
ss >> vertexIndex[i] >>  uvIndex[i] >>  normalIndex[i];