我的.header文件中的所有函数都已声明为public 这是我的代码:
void menu
{
int option = 0;
//cout menu here//
//getting user input to enter their option of menu
cin>>option;
menuChoice(option);
}
void menuChoice(int option)
{
int kiv = 0;
const int size = 50;
while(option) //option just an int to get input from a menu
{
switch(option)
{
case 1: {
while(kiv<size)
{
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
}break;
case2:{
cout<<kiv<<endl; // displays 0
}break;
}
}
}
我已经将kiv声明在顶部,然后在while循环中递增它,但是值保持在while(选项)循环中,所以当我转到情况2时,它假设打印出递增的值,但它显示0,我正朝着正确的方向前进吗?
答案 0 :(得分:0)
这可能是你要找的那个
int kiv = 0;
const int size = 50;
void menuChoice(int option);
void getOption()
{
int option = 0;
cin >> option;
menuChoice(option);
}
void menuChoice(int option)
{
switch (option) {
case 1:
while (kiv < size) {
//codes here to read user inputs then entry increment
++kiv;
}
//cout<<kiv<<endl; // doesn't work here too , it displays nothing
break;
case 2:
cout << kiv << endl; // displays 0
break;
}
getOption();
}
void menu()
{
//cout menu here//
//getting user input to enter their option of menu
getOption();
}
int main(int argc, char **argv)
{
menu();
return 0;
}
答案 1 :(得分:0)
从你的例子中并不完全清楚,但我猜你每次处理menuChoice都会输入该函数,结果你每次都重新初始化kiv。
如果是这种情况,您可能需要将kiv的类型更改为
static int kiv = 0;
这将导致kiv在调用之间保留其值。