我有一个基本的计算程序,我希望当用户想要在他的第一个输入中退出程序而不进行任何计算时,程序就会退出。但是在这里,如果用户在他的第一个输入中输入q for quit/exit
,程序将进入无限循环。有没有办法为用户提供一些单一的退出键,当运行期间任何时候(由用户)输入时退出该程序。除非最外层的循环停止工作,否则最里面的while循环工作正常。
#include "std_lib_facilities.h"
int main() {
double x = 0, y = 0, result = 0;
string operation = " ";
char op = ' ';
cout << "\nInput (e.g. -> 5*6)\nPress q to quit.\n";
while(1) {
cin >> x >> op >> y;
switch(op) {
case '+':
result = x + y;
operation = "sum";
break;
//Other switch cases
case 'q':
exit(1);
default:
cout << "Invalid input.";
break;
}
cout << "The " << operation << " of " << x << " and " << y << " is "
<< result << ".\n\n"
<< "If you have another input, press any character to continue..\n"
<< "Else press q to quit.\n";
// exit or continue program loop
while(cin >> op) {
if(op=='q' || op=='Q')
exit(1);
else
cout << "Provide next set of inputs.\n";
break;
}
}
}
如果用户在第一次尝试时输入q
,那么流将尝试将此值读取到x
,这是一个double
,它将失败并且流的状态将设置为fail
,之后没有其他I / O操作将成功执行,循环将无限运行。
您可以在请求用户继续或退出之前检查流的状态,如果上一个操作失败,则清除流状态:
if(cin.fail())//check if the previous read operation failed
cin.clear();//clear the stream state,so the next cin will read what is in the buffer
while(cin >> op)
...//your other code
试试这个:
boolean quit = FALSE;
while (!quit)
{
...
switch (op)
{
case 'q':
quit = TRUE;
break;
}
}
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char ch;
while(true)
{
cout<<"l.print l "<<endl<<"c.print c "<<endl<<"q. exit"<<endl;
cout<<"enter choice"<<endl;
cin>>ch;
switch(ch)
{
case 'l':
cout<<"You have typed l "<<endl;
break;
case 'c':
cout<<"You have typed c"<<endl;
break;
case 'q':
cout<<"Exit ..." <<endl;
exit(0);
default:
cout<<"Wrong choice "<<endl;
}
}
return 0;
}