为什么这段代码会跳过设置字符串变量的if语句?

Dan*_*nte 1 c++ string if-statement

我正在尝试制作一个项目,询问有关酒店访问的一些问题并重复回答,非常简单.到目前为止,我有这个代码:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    int df;
    int days; 
    string bed;
    string bn;

    cout << "Welcome to C++ Hotel, we have to ask you a few questions about your stay in order to give you the correct rate." << endl;
    cout << "First, what floor would you like to stay on? (We currently have rooms available from floors 2 to 12)" << endl;
    cin >> df;
    while (df > 12 && 2 < df){
        cout << "Sorry, but your answer is invalid, please enter a floor from 2 to 12." << endl;
        cin >> df;
    }
    cout << "Okay, we will register your room on floor " << df << "." << endl;
    cout << "Now, what type of bed will you be requesting during your visit? On floor " << df << " we currently have doubles, queens, or a suite." << endl;
    cin >> bed;
    while (bed != "d" && bed != "q" && bed != "s"){
        cout << "Sorry, but your answer is invalid, please choose between a double, queen or suite by entering either d, q, or s respectively." << endl;
        cin >> bed;
    } 

    if (bed == "d"){
        string bn = "double";
    } 
    if (bed == "q"){
        string bn = "queen";
    }
    if (bed == "s"){
        string bn = "suite";
    }
    cout << "Okay, your room will be on floor " << df << " with a " << bn << "     sized bed!" << endl;
}
Run Code Online (Sandbox Code Playgroud)

我希望用户能够输入d,q或s作为双人床,女王床或套房床尺寸选项,但我也希望重复他们在问题结束时所选择的内容,如果它显示它显然听起来很愚蠢有点像"你选择了大小的床!"

因此,我做了一些if语句,基本上根据用户输入的原始床变量设置了一个新的字符串变量.因此,如果他们将ad设为double,则将bn变量设置为"double",然后在最后cout中调用bn.

但是,代码似乎只是完全跳过了3个if语句,然后在调用变量时它只是空白,代码运行良好,没有错误或警告或任何东西,但我无法弄清楚为什么它只是不识别代码,对我来说似乎没关系?

Moh*_*ain 5

替换string bn = "double";

bn = "double";
Run Code Online (Sandbox Code Playgroud)

您正在声明另一个string具有名称的本地bn并将其设置为某个值,并且bn您打算设置的实际值保持不变.

进一步阅读:C++中的范围