在 while 循环中接受用户输入 [英] Accepting user input in a while loop

查看:45
本文介绍了在 while 循环中接受用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的温度转换程序,允许用户根据需要多次转换温度,直到他们决定通过输入字母e"来结束程序.除了用户输入字母e"的部分外,代码中的其他所有内容都有效.如果我取出最后一个 else 语句,程序将再次从循环开始处开始.如果我把else语句留在里面,当用户输入字母'e'时,else语句认为是无效输入,不结束程序.

I'm trying to create a simple temperature conversion program that allows the user to convert temperatures as many times as they want until they decide to end the program by entering the letter 'e'. Everything else in the code works except the part where the user enters the letter 'e'. If I take the last else statement out, the program just starts at the beginning of the loop again. If I leave the else statement in, when the user enters the letter 'e', the else statement thinks that it is invalid input and does not end the program.

 #include <iostream>

using namespace std;

float celsiusConversion(float cel){     // Calculate celsius conversion
    float f;

    f = cel * 9/5 + 32;
    return f;
}

float fahrenheitConversion(float fah){  // Calculate fahrenheit conversion
    float c;

    c = (fah - 32) * 5/9;
    return c;

}
int main()
{
    char userInput;

        while (userInput != 'e' or userInput != 'E')    // Loop until user enters the letter e
        {

            cout << "Please press c to convert from Celsius or f to convert from Fahrenheit. Press e to end program." << endl;
            cin >> userInput;


            if (userInput == 'c' or userInput == 'C') // Preform celsius calculation based on user input 
                {
                    float cel;
                    cout << "Please enter the Celsius temperature" << endl;
                    cin >> cel;
                    cout << cel << " Celsius is " << celsiusConversion(cel) <<  " fahrenheit" << endl;
                }
            else if (userInput == 'f' or userInput == 'F')  // Preform fahrenheit calculation based on user input
                {
                    float fah;
                    cout << "Please enter the Fahrenheit temperature" << endl;
                    cin >> fah;
                    cout << fah << " Fahrenheit is " << fahrenheitConversion(fah) << " celsius" << endl;
                }
            else    // If user input is neither c or f or e, end program
                {
                    cout << "Invalid entry. Please press c to convert from Celsius, f to convert from Fahrenheit, or e to end program." << endl;
                }
        }
    return 0;
}

推荐答案

我会对您的代码进行 2 处更改:

I'd make 2 changes in your code:

while (userInput != 'e' && userInput != 'E')

而且,就在else"之前(防止退出程序时出现错误信息):

And, just before the "else" (to prevent the error message when exiting the program):

else if (userInput == 'e' or userInput == 'E')
             {
                break;
             }

这篇关于在 while 循环中接受用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆