“如果”语句没有正确执行c ++

时间:2015-06-29 04:10:29

标签: c++ if-statement codeblocks

我对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中完成所有这些。

4 个答案:

答案 0 :(得分:7)

两件事:字符串的比较取决于案例;其次,输入操作符>>在空格上分开,因此您不能使用它来输入多个单词,这会导致您遇到的问题。

您可能想要使用例如std::getline而是一次性阅读整行。

答案 1 :(得分:0)

让您了解自己想做什么。以这种格式设置条件语句总是更安全的选择。可以避免使用=而不是==。

的令人讨厌的错误
#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");
}

答案 2 :(得分:0)

使用getline()函数,因为std::cin仅对空格不接受 使用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...";
}
}

答案 3 :(得分:-1)

使用gets()它将起作用

string answer;

gets(answer);

这将捕获空白区域,直到你按下