2015-03-25 190 views
-2

我的.exe編譯好的程序在CodeBlocks中運行後停止工作, 在選擇了選擇後將cin >> f.name輸入到控制檯後停止 我有一個Windows 8和i使用GNU GCC編譯器這裏是代碼,也許有一個代碼錯誤,我不知道 坦克的關注 :CodeBlocks.exe已停止工作

using namespace std; 
struct employee 
{ 
string name; 
int age; 

}; 
employee employeeList[10]; 
class Stack 
{ 
int pos; 

public: 
Stack(){}; 
void push(employee e) 
{ 
    employeeList[pos] = e; 
    pos++; 

} 
employee pop(int n) 
{ 
    if(n = pos - 1)return employeeList[pos]; 
    if(n < pos - 1) 
    { 
     return employeeList[pos]; 
     for(int j =n; j < pos; j++) 
     { 
      employeeList[pos] = employeeList[pos + 1]; 
     } 

    } 
    pos--; 
} 
string print(int n) 
{ 
    n = pos; 
    cout<<employeeList[pos].name<<endl; 

} 

char menu() 
{ 

    char choice; 
    cout << "Press 1. to push an employee"<<endl; 
    cout << "Press 2. to pop an employee"<<endl; 
    cout << "Press 3. to show an employee"<<endl; 
    cin>> choice; 

    return choice; 


} 


}; 

int main() 
{ 
Stack s; 
char input = s.menu(); 
int j; 

do 
{ 
    switch(input) 
    { 
     case '1' :{employee f; cin>>f.name; s.push(f);}break; 
     case '2' :{int n; cin>>n; s.pop(n);} break; 
     case '3' :{int n; cin>>n; s.print(n);}break; 
    } 
    j++; 
} 
while(j < 10); 


return 0; 

} 
+1

你有關於發生錯誤的任何信息嗎?沒有它,我們很難幫助你。 – Erik 2015-03-25 10:38:45

+0

我不知道爲什麼codeblocks會崩潰,但@lodo是正確的;你沒有初始化'pos'。在你的'push'函數中設置一個斷點,看看會發生什麼 – Zaiborg 2015-03-25 10:52:57

+0

是的,這是問題現在正常工作:不要崩潰,howether我仍然有一些問題,我想一些循環,因爲程序結束只問我一次選擇 – Dado 2015-03-25 12:48:47

回答

2

你做的類「堆棧的實例變量「POS」的不正確初始化」。這意味着最初它可以具有任何價值。如果該值超出了「employeeList」的範圍,那麼您正在訪問不屬於您的內存區域。這可能是一個分割錯誤。