"If" 语句未正确执行 c++

"If" statement does not execute properly c++

关于 c++ 中的 if 语句,我遇到了一个小问题。 这是代码片段:

string answer;
cin >> answer;

if (answer == "stay in bed")
{
   cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom")
{
   cout << "You get up and walk across the hall to the bathroom.";
}
else if (answer == "go downstairs")
{
   cout << "You get up and walk down the stairs to the kitchen.";
}
else
{
   cout << "That is not a valid answer...";
}

当我输入任何值时,我会从 else 语句中获得输出。如 "That is not a valid answer..."

有什么建议吗?我也在 Code::Blocks.

中完成所有这些工作

两件事:字符串的比较取决于大小写;其次,输入运算符 >> 以空格分隔,因此您不能使用它来输入多个单词,这会导致您遇到的问题。

您可能想使用例如std::getline 相反,一次读完一整行。

让你知道你想做什么。以这种格式设置条件语句总是更安全的选择。可以避免使用 = 而不是 == 的严重错误。

#include <iostream>
#include <string>

int main()
{
    std::string answer;
    std::getline(std::cin,answer);

    if ("stay in bed" == answer) {
        std::cout << "You lay there, motionless. Silent.";
    }
    else if ("go to the bathroom" == answer) {
        std::cout << "You get up and walk across the hall to the bathroom.";
    }
    else if ("go downstairs" == answer) {
        std::cout << "You get up and walk down the stairs to the kitchen.";
    }
    else {
        std::cout << "That is not a valid answer...";
    }

    std::cout << '\n';
    system("PAUSE");
}

使用 getline() 函数因为 std::cin only 不接受空格但是 使用 getline 它接受直到出现换行符

#include <iostream>

using namespace std;

int main()
{
string answer;
getline(cin, answer);

if (answer == "stay in bed")
{
    cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom")
{
    cout << "You get up and walk across the hall to the bathroom.";
}
else if (answer == "go downstairs")
{
    cout << "You get up and walk down the stairs to the kitchen.";
}
else
{
    cout << "That is not a valid answer...";
}
}

使用 gets() 它会起作用

string answer;

gets(answer);

这将捕获空格,直到您按下 enter