【问题标题】:Nested If If statement is skipping user's chance to input data for the second question嵌套 If If 语句正在跳过用户为第二个问题输入数据的机会
【发布时间】:2020-09-04 08:18:23
【问题描述】:

更新以更准确地描述问题

C++ 语言 我正在尝试使用嵌套的 if if 语句进行学习(教程如下)。我知道逻辑 && 运算符将是这种情况的理想选择。总之……

当第一个猜测等于第一个答案时,嵌套的 If If 语句正在跳过用户为第二个问题输入数据的机会。当第一次猜测不正确时,一切都按预期运行(问题和用户输入请求都执行)

我可能弄错了,但我觉得一切都与教程相提并论,但我一直遇到我提到的问题。有人有答案吗? :)

谢谢:)



#include <iostream>
#include <string>

int main ()
{
std:: string variable_one_guess;
std:: string variable_two_guess;
std:: string variable_one_answer = "The answer for one";
std:: string variable_two_answer = "The answer for two";

std:: cout << "Guess the variable one value\n";
std:: cin >> variable_one_guess;
std:: cout << "Guess the variable two value\n";
std:: cin >> variable_two_guess;


if (variable_one_guess == variable_one_answer) // I am aware I can just combine both if statements using the logical
                                      //  && operator but I need this to work for learning purposes

{

    if(variable_two_guess == variable_two_answer)

    {std:: cout << "Correct!\n";}

}

}

【问题讨论】:

  • std:: cin &gt;&gt; variable_one_guess; 读取一个以空格分隔的单词。使用getline(std::cin, variable_one_guess);
  • @Quentin 这看起来像是一个答案。甚至是解释过的。
  • 您可以使用The_answer_for_one(注意没有空格)作为秘密和输入来测试昆汀的解释。如果可行,则应用 Quentins 提出的代码,看看它是否可以在有和没有空格的情况下工作。如果是这样,您可以创建自己的答案(甚至接受它)。这样就可以将其排除在未回答的问题列表之外。
  • 昆汀的回答有效且有道理,我知道的比这更好! XD 本教程仅使用 int,而我使用字符串进行练习并忘记了这一点。感谢你们的帮助:) PS 两天无法接受我的回答。

标签: c++ if-statement nested-if


【解决方案1】:

Quentin 正确地让我注意到了 getline 函数,该函数有效。 cin 读取一个以空格分隔的单词。所以我不得不将 cin 替换为 getline 函数。

//code
std:: cin >> variable_one_guess;
// code
std:: cin >> variable_two_guess;
//code

被替换为

//code
getline(std::cin, variable_one_guess);
// code
getline(std::cin, variable_two_guess);
//code

【讨论】:

    猜你喜欢
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多