-1

Updated to describe the issue more accurately

C++ Language I am trying to use a nested if if statement for learning purposes (tutorial following along with). I am aware the logical && operator would be ideal for this situation. Anyways...

The nested If If statement is skipping the user's chance to input data for the second question when the first guess equals the first answer. When the first guess is incorrect, everything runs as intended (both questions and user input request execute)

I could be mistaken but I feel everything is on par with the tutorial yet I keep encountering the issue I mentioned. Anyone got an answer? :)

Thanks :)



#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";}

}

}
  • 2
    `std:: cin >> variable_one_guess;` reads a single, whitespace-separated word. Use `getline(std::cin, variable_one_guess);`. – Quentin Sep 04 '20 at 08:41
  • @Quentin That looks like an answer. Even an explained one. – Yunnosch Sep 04 '20 at 08:47
  • You can test Quentins explanation by using `The_answer_for_one` (note the absence of whitespace) as secret and input. If that works then apply Quentins proposed code and see if it works then with and without whitespace. If it does, you can create your own answer (and even accept it). That would get this out of the list of unanswered questions. – Yunnosch Sep 04 '20 at 08:52
  • Quentin's answer works and makes sense, I know better than that! XD The tutorial was using just int and I was using strings for practice and forgot about that. Thanks to you both for the help :) PS unable to accept my answer for two days. – UV Bakes and Beyond Sep 04 '20 at 09:39

1 Answers1

0

Quentin correctly brought the getline function to my attention which works. cin reads a single, whitespace-separated word. So I had to replace cin the the getline function.

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

was replaced as

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