为什么在打印函数中使用do while循环时会得到一个无限循环



我正在尝试制作一个包含不同函数的菜单,这些函数应该在用户输入"Q"或"Q"字符之前运行。当我尝试运行程序时,它会一直循环默认的开关情况。我用错循环了吗?

#include <iostream>
#include <vector>
using namespace std;

bool getout{false};
char cases ;
void menu(){
cout << "nnP - Print NumbernA - Add NumbernM - Display mean of the numbernS - Display the smallest numbernL - -Display the largest numbernQ - QuitnnEnter your choice: " << endl;
}
char read(){
cin>> cases;
}
int main(){
do{
void menu();
void read();
switch (cases){
case 'p':
case 'P':  void print();
break;

case 'S':
case 's':
void smallest();
break;
case'Q':
case 'q':
getout=true;
break;

default:
cout<<"Please input a valid option";
}//switch braces
}
while (getout==false);
return 0;}

您的read((函数虽然被标记为返回char,但不会返回任何内容。您在主函数中也错误地调用了该函数。这是罪魁祸首。

删除单词void。

我附上了你代码的修改版本。它将全局变量移动到主函数中(尽可能避免全局变量(,并修复读取函数以返回字符。我永远无法判断问题中糟糕的格式是复制粘贴问题,还是你的代码有那么草率,但无论哪种情况,我都格式化了它。

#include <iostream>
#include <vector>
void menu() {
std::cout
<< "nnP - Print NumbernA - Add NumbernM - Display mean of the "
"numbernS - Display the smallest numbernL - -Display the largest "
"numbernQ - QuitnnEnter your choice: ";
}
char read() {
char choice;
std::cin >> choice;
return choice;
}
int main() {
bool getout{false};
do {
menu();
char cases = read();
switch (cases) {
case 'p':
case 'P':
void print();
break;
case 'S':
case 's':
void smallest();
break;
case 'Q':
case 'q':
getout = true;
break;
default:
std::cout << "Please input a valid option";
} // switch braces
} while (getout == false);
return 0;
}

相关内容

最新更新