2016-10-30 68 views
-2

我這裏有C++分段故障switch語句CIN

string shapename; 
bool warpspace; 
const int size = 100; 
ShapeTwoD shape2D[size]; // ShapeTwoD is a parent class 
int number =0; 
static int count = 0; 

while(choice !=999) 
{ 

    switch(choice) 
    { 
     case 1: 
     { 
      cout<<"[Input sensor data]"<<endl; 
      cout<<"Please enter name of Shape:"; 
      cin>>shapename; 
      shape2D[size].setName(shapename); //segmentation fault 
      cout<<"Please enter special type:"; 
      cin>>warpspace; 
      shape2D[size].setContainsWarpSpace(warpspace); 
      cin.clear(); 
      cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
      if(shapename == "Square" || shapename == "square") 
       { square.setSquareCord(); count++; } 
      if(shapename == "Rectangle" || shapename == "rectangle") 
       { rect.setRectangleCord(); count++; } 
      mainmenu(); 
      cin>>number; 
      option(number); 
     }break;//there are still multiple cases 
    } 
} 

當我嘗試編譯並運行這段代碼,它給了我分割錯誤之後我進入形狀please enter name of shape :我做了什麼錯在這裏?

+0

解決這樣的問題的合適的工具是調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

回答

2

您正在訪問出側陣列邊界:

shape2D[size]. 
     ^^^^ 

有效陣列索引是從0到大小-1