C++ 结构向量,读取访问冲突

C++ Vector of structs, read access violation

编辑:For 循环没有结束条件。新手错误.

我正在为学校做作业,使用 MS VS,它有非常具体的 要求。我们从 txt 文件中读取形状名称和尺寸,为每个形状创建一个结构,仅将尺寸作为成员,并使用支持函数计算 area/volume 并输出结果。必须有 4 个循环:

我的程序只有方块的代码:

#include <iterator>
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include <fstream>
#include <map>
#include <cmath>
#include <cstdlib>

using namespace std;

int main()
{

  string line, str;
  double d1, d2, d3;
  map < string, int > shapes;
  vector<void*> myBag;
  vector<char> myBagType;

  shapes.insert(pair<string, int>("SQUARE", 1));

  ifstream shapesin("TextFile1.txt");
  ofstream shapesout("TextFile2.txt");

  if (!shapesin || !shapesout)
  {
    cout << "Unable to open file\n";
  }

  while (getline(shapesin, line)) 
  {
    d1 = d2 = d3 = 0;
    vector<string> token = parseString(line);

    if (token.size() >= 1) 
    {
      str = token[0];
      switch (shapes[str])
      {
      case 1: //Square
      {
        Square* s = new Square;
        myBag.push_back(s);
        myBagType.push_back('S');
        if (token.size() < 2) 
        {
          s->side = 0;
          break;
        }
        else
        {
          str = token[1];
          d1 = atof(str.c_str());
          s->side = d1;
        }
        break;
      }
    }
  }
  for (unsigned int i = 0; myBag.size(); i++)
  {
    if (myBagType[i] == 'S')
    {
      Square* aSquare = reinterpret_cast<Square*>(myBag[i]);
      Square& bSquare = *aSquare;
      outputSquare(cout, bSquare);
    }
  }

  for (unsigned int i = 0; myBag.size(); i++)
  {
    if (myBagType[i] == 'S')
    {
      Square* aSquare = reinterpret_cast<Square*>(myBag[i]);
      Square& bSquare = *aSquare;
      outputSquare(shapesout, bSquare);
    }
  }

  for (unsigned int i = 0; myBag.size(); i++)
  {
    if (myBagType[i] == 'S')
    {
      Square* aSquare = reinterpret_cast<Square*>(myBag[i]);
      delete aSquare;
    }
  }

  shapesin.close();
  shapesout.close();
  }
}

vector<string> parseString(string str)
{
  stringstream s(str);
  istream_iterator<string> begin(s), end;
  return vector<string>(begin, end);
}

void outputSquare(ostream& shapesout, const Square& x)
{
  double perim, area;
  perim = (x.side * 4); //exception thrown here
  area = (x.side * x.side);

  shapesout << "SQUARE " << "side=" << x.side;
  shapesout.setf(ios::fixed);
  shapesout.precision(2);
  shapesout << " area=" << area << " perimeter=" << perim << endl;
  shapesout.unsetf(ios::fixed);
  shapesout.precision(6);
}

txt文件输入为:

正方形 14.5 344
正方形
矩形 14.5 4.65
方面 圆 14.5

BOX x 2 9

立方体 13 专栏 1 2 3 气缸 2.3 4 56 糖果

SPHERE 2.4
气缸 1.23
气缸 50 1.23 三角形 1.2 3.2
棱镜 2.199 5

EOF

我知道我访问结构成员的方式有问题 x.side 但我尝试过的所有其他方式都无法编译,因为这至少会输出第一行。我读过其他类似的问题,但找不到像这样的问题。非常感谢您的帮助。

for (unsigned int i = 0; myBag.size(); i++)

无终止条件

for (unsigned int i = 0; i < myBag.size(); i++)

固定