如何使用用户提示在switch case实现中退出?

问题描述 投票:1回答:3

我有一个基本的计算程序,我希望当用户想要在他的第一个输入中退出程序而不进行任何计算时,程序就会退出。但是在这里,如果用户在他的第一个输入中输入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;
        }
    }
}
c++ infinite-loop
3个回答
2
投票

如果用户在第一次尝试时输入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

0
投票

试试这个:

boolean quit = FALSE;
while (!quit)
{
  ...
  switch (op)
  {
    case 'q':
      quit = TRUE;
      break;
  }
}

0
投票
#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.