程序识别第一个文本输出,但不识别第二个文本输出

时间:2016-03-30 06:40:43

标签: c++ loops c++11

我对C ++编程很新,所以这可能是一个新手的错误。但。 (为什么我不能隐藏其余的代码......我想展示我正在做的所有......)

首先,我的代码的开头看起来像这样(标题等,加上前几行代码)

#include <iostream>
#include <string>

using namespace std;

string command;    
string playername; 
char response;     

string object;  

int main()
{

    do
    {          
       cout << "What is your name? "; 
       cout << endl;

       cin >> playername; 
       cout << endl;

       cout << "Your name is " << playername << "? (Y/N)" << endl; 
       cout << endl;
       cin >> response; 

       cout << endl;
       cout << endl;

    } while ((response != 'y')&&(response != 'Y')); 
}

接下来是问题所在:

do
{  
    cout << endl;
    cout << "What will you do?";  
    cout << endl;

    cin >> command >> object; 

    if ((command == "look")&&(object == "door")) 
       cout << "You look at the door. It appears to be but a simple wooden door
       with a brass handle for opening and shutting. "; 

    else if ((command == "Open")&&(object == "door")) 
       cout << "You open the door and proceed to the next room";

    } while ((command == "look")&&(command == "Look")); 
}

当我输入“look”和“door”(作为命令和对象)时,我的程序将会识别并以适当的“It is a door”行响应。但是,当我输入“打开”和“门”时,它只接受它并结束程序,而不显示文本。

如果我有任何方法可以纠正这一点,我会非常感激。

谢谢!

编辑:为了便于阅读 EDIT2:将最后一行更改为

}while ((command == "look")||(command == "Look")); 

我得到: the bulwarky that is this code

3 个答案:

答案 0 :(得分:2)

如果(command == "look")&&(command == "Look")同时是command "look",那么表达式"Look"才会成立,这是不可能的,将成为条件false

您应该使用逻辑(command == "look")||(command == "Look")

答案 1 :(得分:0)

您的问题取决于“打开”和“打开”之间的差异。这真的很难,所以检查两种情况下的所有字符串。所以也许你可以使用std :: toupper函数。

尝试这样的事情:

if(toupper(command) == toupper("open") && toupper(object) == toupper("door"))

修改:参考toupper-function

答案 2 :(得分:0)

您的阅读和打印代码只能使用一次,因为您的条件无效。我假设如果你输入&#34; Open&#34;和&#34;门&#34;作为您的第一个命令,您将获得打开的文本,然后程序停止。

程序一旦读取代码的原因是因为do-while循环以这种方式构建。它将执行一次循环,然后通过查看while(..)语句是否仍然有效来检查是否需要再次执行。

以下是do-while循环的一些额外信息。 http://www.tutorialspoint.com/cplusplus/cpp_do_while_loop.htm

引自链接网站:

  

C ++中do ... while循环的语法是:

do 
{ 
   statement(s);
}
while( condition ); 
  

注意有条件的   表达式出现在循环的末尾,所以语句中的语句   在测试条件之前循环执行一次。

我不确定你想要在你的程序中使用哪种行为;你什么时候想停止这个节目?如果您想继续查看并打开门,我建议您将while(..)语句更改为

while (command != "stop");

这样程序将继续,直到您输入单词&#34; stop&#34;