#include <iostream>
using namespace std;
void menue()
{
cout<<"Choose an option"<<endl;
cout<<"========================"<<endl;
cout<<"1. Open"<<endl;
cout<<"1. Close"<<endl;
cout<<"1. Exit"<<endl;
}
void menueOptions()
{
do
{
int input;
cout<<"Enter selection here: "<<flush;
cin >> input;
switch(input)
{
case 1:
cout<<"Opening..."<<endl;
break;
case 2:
cout<<"Closing..."<<endl;
break;
case 3:
cout<<"Exiting..."<<endl;
break;
default:
cout<<"Invalid input"<<endl;
}
}
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}
int main()
{
menue();
menueOptions();
return 0;
}
答案 0 :(得分:2)
变量input
在do-while语句的块范围(compound语句)中声明。
do
{
int input;
//...
}
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}
因此,在do-while语句的情况下,不得在范围之外使用它。
(注意:即使do-while语句不使用复合语句,它在do和while之间也有其自己的块范围。根据C ++ 17标准(8.5迭代语句)
2迭代语句中的子语句隐式定义了一个 块作用域(6.3),每次通过 环。如果迭代语句中的子语句是单个 语句,而不是复合语句,就好像它已被重写 成为包含原始语句的复合语句。
-尾注)
在do-while语句之前声明它
int input;
do
{
//...
}
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}