0

I'm trying to use std::cin whilst having one option loop back to the start. The loop works perfectly but when I add in an extra option to one of the if statements then type that in, it doesn't think that what I chose is an option.

#include <iostream>
#include <string>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;

int main() {  
    string  choice;
    char restart;

    do {
        choice.clear();
        cout << "Which do you take? " << endl;
        cin >> choice;

        if (choice == "all") {
            //cout code
            restart = 'y';
        }
        else if (choice == "dagger" || choice == "the dagger") {
            choice.clear();
            cout << "You pick up the dagger" << endl << endl;
            return 0;
        }
        else {
            choice.clear();
            cout << "That isn't an option, pick again... "<< endl << endl;
            sleep_for(1s);
            restart = 'y';
        }

    } while (restart == 'y');
}

When I type in "dagger", it works just fine, but when I type in " the dagger" it says runs the else code, then loops back to "Which do you take" and then chooses "dagger" instantly.

6
  • 1
    cin >> choice reads one word, so given the dagger, it reads the and leaves dagger in the stream for later. Commented Aug 4, 2018 at 21:56
  • 1
    The >> operator reads words, not lines. Use std::getline instead. See en.cppreference.com/w/cpp/string/basic_string/getline Commented Aug 4, 2018 at 21:56
  • 2
    Debugging note: When you want to know what's up with an input, the first thing you should do is print out the input. Kills most bugs dead instantly. Commented Aug 4, 2018 at 21:58
  • Thank you both so much! I didnt know that about cin. Commented Aug 4, 2018 at 22:07
  • @user4581301 — choice is std::string, not a stream. choice.clear(); is correct. Commented Aug 5, 2018 at 0:20

1 Answer 1

1

You're using std::cin with the >> operator. This operator reads formatted input (words) instead of unformatted input (lines). Rather than reading "the dagger", your program is simply reading "the", and leaving "dagger" in the input buffer for later.

To read unformatted input to choice, use std::getline(std::cin, choice); instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.