C++ 读取字符串字符时出错,访问冲突
所以我正在努力让这个项目在学校的作业中发挥作用。现在有多个实例显示,如果我尝试运行它,它会显示 Project5.exe中0x000D3619处的未处理异常:0xC0000005:访问冲突读取位置0x00000000 这里发生了什么?我知道这与我打开文件和向量的方式有关。但我不知道是什么 以下是我的主要功能:C++ 读取字符串字符时出错,访问冲突,c++,visual-studio,class,vector,C++,Visual Studio,Class,Vector,所以我正在努力让这个项目在学校的作业中发挥作用。现在有多个实例显示,如果我尝试运行它,它会显示 Project5.exe中0x000D3619处的未处理异常:0xC0000005:访问冲突读取位置0x00000000 这里发生了什么?我知道这与我打开文件和向量的方式有关。但我不知道是什么 以下是我的主要功能: int main() { vector<shape*> shapes; shapes.resize(1000); ifstream fs; s
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;
}
intmain()
{
矢量形状;
形状。调整大小(1000);
IFFS;
字符串filen=“shapers.txt”;
fs.open(filen.c_str());
字符串obj=“”;
fs>>obj;
//int j=0;
而(!fs.fail()){
如果(obj==“球体”){
双半径;
fs>>半径;
形状。推回(新球体(半径));
//形状[j]=新球体(半径);
}else if(obj==“长方体”){
双宽、双高、双长;
fs>>宽度>>长度>>高度;
形状。向后推(新长方体(宽度、长度、高度));
//形状[j]=新长方体(宽度、长度、高度);
}否则如果(obj==“气缸”){
双半径,高度;
fs>>半径>>高度;
形状。向后推(新圆柱体(半径、高度));
//形状[j]=新圆柱体(半径、高度);
}
fs>>obj;
//j++;
}
fs.close();
对于(int i=0;idisplay();
cout你要做的第一件事是:
shapes.resize(1000);
然后,当你阅读形状时,你调用
shapes.push_back(...
所以你的向量的大小是10011002…等等。前1000个形状指针将给你访问冲突,正如你所看到的
你要么直接打电话
shapes.reserve(1000)
在一开始,或者坦白地说,完全忽略这一行,因为您只需要添加日志记录或使用调试器。调整指针向量的大小很便宜,所以删除这一行可能是最好的。@DavidSchwartz同意。如果他们确实需要1000或10000个指针,那么可能需要保留
。但是对于5个指针(在他们的例子中)最好让它自己调整大小。我将它改为简单的“向量形状;”。现在它给了我一条中止消息,因为它说向量下标超出了范围。去掉