我一直在試圖弄清楚爲什麼我的代碼在過去的幾個小時內無法正常工作。一切看起來都很好,除非我不知道。我問過我的教授,但他似乎無法弄清楚。此代碼將完全忽略推動成員函數中的if else語句,並在達到極限後繼續推送(本例中爲5個元素)。當它遍歷第五個元素時,我檢查頂部,它顯示第一個實現(元素0)。我嘗試通過在範圍解析中切換類之外的成員函數來更改我的代碼,但它仍然沒有用。一個不同的眼睛將不勝感激。堆棧數組中的C++ - 問題
#include <iostream>
#include <cctype>
using namespace std;
class Stack
{
private:
static const int size = 5;
double myarr[size];
int t;
public:
Stack() { t = -1; }
void push(double element);
void pop();
void top();
void menu();
};
void Stack::push(double element)
{
if (t < size) {
t++;
myarr[t] = element;
}
else
cout << "Stack Limit Reach !!!" << endl;
}
void Stack::pop()
{
if (t >= 0) {
cout << "Element : " << myarr[t] << " was popped off the Stack " << endl;
t--;
}
else
cout << "No more elemnts in the Stack !!!" << endl;
}
void Stack::top()
{
if (t >= 0) {
cout << "Element : " << myarr[t] << " is at the top of the Stack " << endl;
}
else
cout << "No more elemnts in the Stack !!!" << endl;
}
void Stack::menu()
{
char choice = 'y';
int pick;
double elem;
while (toupper(choice) == 'Y');//while(choice == 'y' || choice == 'Y');
{
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Top" << endl;
cout << "4. Exit" << endl;
cin >> pick;
switch (pick)
{
case 1:
cout << "Enter the element: ";
cin >> elem;
cout << endl;
push(elem);
break;
case 2:
pop();
break;
case 3:
top();
break;
case 4:
choice = 'N';
break;
default:
cout << "Please select 1-4" << endl;
}
system("pause");
}
}
int main()
{
Stack obj;
obj.menu();
};
抱歉給一個看似滑稽的評論(它不是意),但你嘗試通過它與調試器步進? 'while(toupper(choice)=='Y');'不應該以分號結尾,這可能是問題嗎? –