如何分配枚举值给用户定义的双变量??c++

How to assign an enum value to a double variable defined by the user ?? C++

本文关键字:定义 变量 c++ 给用户 何分配 分配 枚举      更新时间:2023-10-16

你好,我是一名学生,所以我想说对不起,如果我写得很累,请随时纠正我。

我有以下问题,我试图将enum int值分配给另一个双变量以进行一次乘法。因此变量costOfRoom应该取属于枚举的值D或T或S。(D = 200, T = 150 = 110)

这必须由用户完成。

但不能找到任何方法,我试图使第二个变量的字符串类型,但它不工作了。它只会像字符串一样接受字符(

)

也试过cin >> type_Ofroom costofroom ;但我认为这是在Java中使用的?

搜索了论坛也没有类似的答案:(

程序运行正常,没有任何编译错误:)

感谢您的宝贵时间

/* build a software system which will allow a hotel receptionist,
to enter in bookings for guests who come to the desk.
The system should display the room options as:
Room        Price       Code
---------------------------------------------------------------
Deluxe Room £200         D
Twin Room       £150     T
Single      £110         S
The receptionist should be prompted to enter in the room type and the number of 
nights a guest wishes to stay for and then calculate the amount
they need to pay. 
   */
// solution 
#include <iostream>
using namespace std;
int main() {
    // decleration of variables 
    double number_OfDays = 0, Totalcost = 0, costofroom = 0;
    enum   type_Ofroom { D = 200, T = 150, S = 150 };
    cout << "enter the type of the room " << endl << endl;
    //input of room type
    cin >> costofroom; // **here is the problem**  i am trying to give the 
                       //    values of the enum varaiable 
                        // it should have D or T or S but i cant  make it
    cout << "enter the number of the days " << endl << endl;
    //input of days
    cin >> number_OfDays;
    // calculation 
    Totalcost = costofroom * number_OfDays;
    // result 
    cout << "the costumer has to pay " << Totalcost << " pounds" << endl << endl;
    return 0;
}

您可以读取double,然后检查您的enum值:

//input of room type
while (1)
{
    cin >> costofroom;
    if (costofroom == 0.0)
        costofroom = D;
    else if (costofroom == 1.0)
        costofroom = T;
    else if (costofroom == 2.0)
        costofroom = S;
    else
    {
        cout << "You didn't enter a valid option" << endl;
        continue;
    }
    break;
}

但是,最好读入int,然后再设置double

double costofroom;
int option;
...
//input of room type
while (1)
{
    cin >> option;
    if (option == 0)
        costofroom = D;
    else if (option == 1)
        costofroom = T;
    else if (option == 2)
        costofroom = S;
    else
    {
        cout << "You didn't enter a valid option" << endl;
        continue;
    }
    break;
}

用户只能输入字符。Cin将数字组转换为整型(例如123)或双精度(例如123.5)。它还将处理std::字符串(例如hello)或单个字符(例如c)的非数字分组。

一旦有了用户的输入,就可以将它们转换为枚举。您可以使用if语句,case语句或其他类型的表查找来完成此操作。