读取字符串字符和访问冲突时出错

时间:2014-12-08 20:33:58

标签: c++ visual-studio class vector

所以我正努力让这个课程适合在学校完成作业。现在它有多个实例,如果我只是尝试运行它,那么

Project5.exe中0x000D3619处的未处理异常:0xC0000005:访问冲突读取位置0x00000000。

这里发生了什么?我知道它与我打开文件和矢量的方式有关。但我不知道是什么。

这是我的主要功能:

int main()
{
    vector<shape*> shapes;
    shapes.resize(1000);

    ifstream fs;
    string filen = "shapers.txt";
    fs.open(filen.c_str());
    string obj="";
    fs>>obj;
    //int j=0;
    while (!fs.fail()) {
      if (obj == "Sphere") {
        double radius;
        fs>>radius;
        shapes.push_back(new sphere(radius));
        //shapes[j] = new sphere(radius);
      } else if (obj == "Cuboid") {
        double width, height, length;
        fs >> width >> length >> height;
        shapes.push_back(new cuboid(width,length,height));
        //shapes[j] = new cuboid(width,length,height);
      } else if (obj == "Cylinder") {
        double radius, height;
        fs >> radius >> height;
        shapes.push_back(new cylinder(radius,height));
        //shapes[j] = new cylinder(radius,height);
      }
      fs >> obj;
      //j++;
    }
    fs.close();


    for (int i=0; i<=5; i++)
    {
        shapes[i]->display();
        cout<<endl;
    }
    maxSurfaceArea(shapes);

    expandAll(2);

    for (int i=0; i<=5; i++)
    {
        shapes[i]->display();
        cout<<endl;
    }
    //cout<<shapes[0]<<" "<<shapes[1]<<" "<<shapes[2]<<" "<<shapes[3]<<" "<<shapes[4]<<" "<<shapes[5]<<endl;



    pause_215(true);
    return 0;

}

1 个答案:

答案 0 :(得分:2)

您要做的第一件事是:

shapes.resize(1000);

然后当您阅读形状时,请致电

shapes.push_back(...

所以你的矢量大小为1001,1002 ......等。前1000个形状指针会让你看到违规行为。

您应该致电

shapes.reserve(1000)

一开始,或坦率地说完全离开那条线,因为你只期待&lt; 10个形状(数量级)