我有这个 C++ 代码,我正在尝试执行以下操作:
提示用户输入“p”播放或“q”退出,如果用户输入任何“p”程序将继续,如果用户输入“q”程序将终止,如果他们输入无效输入,它也会终止。我该怎么做?
谢谢,
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
int Umain = 0;
double Atemp = 0;
double Utemp = 0;
double Working = 0;
double Total = 0;
char Answer = 'x';
void displayOverview ();
void playOrQuit();
void promptNumber();
int main(){
displayOverview();
playOrQuit();
promptNumber();
return 0;
}
void displayOverview(){
}
void playOrQuit(){
string playOrNot;
cout << "If you want to play please press 'p' for play, and 'q' if you wish to quit\n";
cin >> playOrNot;
if(playOrNot == "p"){
cout << "Awesome, lets start playing !!! \n";
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
}
}
void promptNumber(){
do{
cout << "Please Enter numbers between 1 and 12: ";
cin >> Umain;
cout << "\n";
for (Utemp = Umain; Utemp > 0; Utemp--)
{
cout << "Please enter a number: ";
cin >> Atemp;
Working = (Working + Atemp);
}
}while (Answer == 'y');
}
最佳答案
只需在检测到“q”被按下后添加对 exit
的调用:
}if(playOrNot == "q"){
cout << "Alright then, see you soon !!\n";
exit(0); // <=== Add this here
传统上以 0
退出意味着程序以预期的方式退出并且没有任何错误。
关于c++ - 如果用户输入 "q",程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402554/