vendredi 6 septembre 2019

if statement not executing properly? or is loop incorrect?

In this program I am opening a file and putting each line into a vector. In that vector, I am text parsing and turning each item into tokens. I know the issue is not here because when I use cout, the tokens are outputted correctly. Earlier the code was working for me, but I am not sure if I have changed something to make it stop working. I am not sure if the issue is how I am comparing the strings or if it's the loop or if it's the if statement that is not executing properly or if it's the function itself.

Each a[0] is a string like SQUARE or CYLINDER. (But for simplicity I have only used SQUARE below.) a[i+1] is some kind of dimension for the shape and I am converting a[i+1] to a double number for calculations.

void calculate(vector<string> a)
  {
  for(int i = 0; i < a.size(); i++){
    if(strcmp(a[i].c_str(), "SQUARE") == 0)
    {
      double SIDE = atof(a[i+1].c_str());

      cout << a[i] << " side = " << a[i+1] << " area = " << (SIDE*SIDE) << " perimeter = " << (4.0*SIDE) << endl;
    }
    else
      cout << "invalid";
  }

I expect to see

SQUARE side = 14.5 area = 210.25 perimeter = 58
SQUARE side = 13 area = 169 perimeter = 52 

etc. but instead I see

SQUARE side = 14.5 area = 210.25 perimeter = 58
invalidinvalidSQUARE side = 14.5 area = 210.25 perimeter = 58

Aucun commentaire:

Enregistrer un commentaire