1

I am trying to read a text file with different amount of variables on each line and set the correct values to a vector using sstream.

/*Example file
 "f 1 2 3"
 "f 4 5 6 7"  */

ifstream infile(file);
string line;
char a;
int i=0;v,x,y,z;

while(getline(infile,line))
{
    istringstream iss(line)

    if(line[0]=='f')
    {       
         if(iss>> a >> v >> x >> y) 
         {    
              poly[i].face[0]=v;
              poly[i].face[1]=x;
              poly[i].face[2]=y;
              poly[i].four=false;
         }
         else if(iss>> a >> v >> x >> y >> z) //this doesn't seem to get called, ever.
         {
              poly[i].face[0]=v;
              poly[i].face[1]=x;
              poly[i].face[2]=y;
              poly[i].face[3]=z;
              poly[i].four=true;
         }
        poly.push_back(Poly());
        i++;
    }

}

code works for lines with 3 variables, but not for lines with 4 variables.

user3085497
  • 121
  • 2
  • 6

2 Answers2

1

This is because the first bunch of input already read those variables in successfully, and the else part was never reached. Since the start of the line is always the same, as is where you store those values, you can do this:

 if(iss >> a >> v >> x >> y) 
 {    
      poly[i].face[0]=v;
      poly[i].face[1]=x;
      poly[i].face[2]=y;
      poly[i].four=false;

      if(iss >> z)
      {
          poly[i].face[3]=z;
          poly[i].four=true;
      }
 }
paddy
  • 60,864
  • 6
  • 61
  • 103
0

Using >> advances the stream, so it will change what the next call to >> does. If the first if(...) fails, the stream iss will have been modified so that the else if (...) fails too.

Instead, you can do something like this:

if(iss >> a >> v >> x >> y) 
{    
      poly[i].face[0]=v;
      poly[i].face[1]=x;
      poly[i].face[2]=y;

      if (iss >> z) // if we can read the fourth value...
      {
          poly[i].face[3]=z;
          poly[i].four=true;
      }
      else
      {
          poly[i].four=false;
      }
}
porges
  • 30,133
  • 4
  • 83
  • 114