switch case语句中的循环

Loop in a switch case statement

本文关键字:循环 语句 case switch      更新时间:2023-10-16

我需要帮助验证switch case语句,我需要它来检查用户输入的内容,如果不匹配,则拒绝它,并告诉他们再次执行。我现在有一个部分工作,但会拒绝第一个数字,然后在尝试输入另一个数字时中断。帮助如果您需要查看整个程序,只需询问即可。

#include "stdafx.h"
#include "cstdlib"
#include "iostream"
#include "windows.h"
#include "cmath"

using namespace std;
int main(int argc, char* argv[])
{

float ALT0();
float ALT5000();
float ALT10000();
float ALT15000();
float ALT20000();
float ALT25000();
float ALT30000();
float ALT35000();
float ALT40000();
void an_answer(float a);
char Restart;
char op;
float answer;
do
{
cout << "ntttOperational Flight Plann" << endl;
cout << "For the saftey of everyone on board, there will be 100 kg added to the overallnamount to give the aircraft more fuel incase of a head on wind or delays at the landing airport.n" << endl;
cout << "Select Altitude the aircraft will fly at: " << endl;
cout << "0 for 0ftn1 for 5000ftn2 for 10000ftn3 for 15000ftn4 for 20000ftn5 for 25000ftn6 for 30000ftn7 for 35000ftn8 for 40000ft" << endl;
cin >> op;
switch (op)
{
case'0':
    answer=ALT0();
    break;
case '1':
    answer=ALT5000();
    break;
case '2':
    answer=ALT10000();
    break;
case '3':
    answer=ALT15000();
    break;
case '4':
    answer=ALT20000();
    break;
case '5':
    answer=ALT25000();
    break;
case '6':
    answer=ALT30000();
    break;
case '7':
    answer=ALT35000();
    break;
case '8':
    answer=ALT40000();
    break;
    default:
        cout << "You must enter a number from 0-8" << endl;
        cin >> op;
    break;
}
an_answer(answer);
cout << "Do you want to do another calculation? Press Y for yes and anything else to quit.";
cin >> Restart;
} while (Restart=='y' || Restart=='Y');
//system("PAUSE");
//return EXIT_SUCCESS;
}

我打赌你是在输入数字后再输入。您的第一个cin >> op读取数字,但第二个读取回车键。如果要读取整行,请使用读取整行的函数。

或者,将第二个cin >> op向上移动到switch语句之前。如果有人在点击回车键之前输入了多个字符,则此功能将中断,但在其他情况下会起作用。