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.
cin >> choicereads one word, so given the dagger, it reads the and leaves dagger in the stream for later.>>operator reads words, not lines. Use std::getline instead. See en.cppreference.com/w/cpp/string/basic_string/getlinechoiceisstd::string, not a stream.choice.clear();is correct.