Reputation: 53
(Sorry, I know this question has been asked [and answered] before, but none of the solutions worked for me, because something about the way my code is set up is wonky and I have no idea which part that is).
Okay, I have a function, get_cookie_type, which lets the user choose from 3 types of cookie--Chocolate chip, sugar, and peanut butter. After they type an input, I make sure that whatever they put in is one of those 3 choices, and throw an error message if not. The problem is that for the "Chocolate chip" and "Peanut butter" choices, I always get the "bad input" message, clearly because they have spaces, and I have no idea how to get around this. I've tried messing around with cin.getline, but it still gives me the bad input message.
WHY IS THIS
string get_cookie_type()
{
std::string cookieType;
cout << "What kind of cookie is the customer asking for? (Enter 'Chocolate chip', 'Sugar', or 'Peanut butter', exactly, without quotes).\n";
std::getline(std::cin, cookieType);
while (cookieType !="Chocolate chip" && cookieType != "Sugar" && cookieType != "Peanut butter")
{
cout << "\nYou put your data in wrong, try again.\n";
cin >> cookieType;
}
return cookieType;
}
Upvotes: 0
Views: 1258
Reputation: 52395
Use std::getline(std::cin, cookieType)
in the while loop. operator>>
will stop at the very first space while std::getline
by default stops at the newline.
It looks like you have characters left in the input stream. Add the following line before the first call to std::getline
(and include <limits>
header):
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Upvotes: 1
Reputation: 7458
You should place std::getline(std::cin, cookieType); inside while. try:
std::getline(std::cin, cookieType);
while (cookieType !="Chocolate chip" && cookieType != "Sugar" && cookieType != "Peanut butter")
{
cout << "\nYou put your data in wrong, try again.\n";
std::getline(std::cin, cookieType);
}
actually, do{}while would be more appropriate.
Upvotes: 1