2015-03-25 186 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”的范围,那么您正在访问不属于您的内存区域。这可能是一个分割错误。