(抱歉,我知道这个问题之前有人问过 [并回答过],但没有一个解决方案对我有用,因为我的代码设置方式有点不稳定,我不知道那是哪一部分) .
好的,我有一个函数 get_cookie_type,它允许用户从 3 种类型的 cookie 中进行选择——巧克力片、糖和花生酱。在他们键入输入后,我确保他们输入的内容是这 3 个选择之一,如果不是,则抛出错误消息。 问题是对于“巧克力片”和“花生酱”的选择,我总是收到“输入错误”的消息,显然是因为它们有空格,我不知道如何解决这个问题。 我试过弄乱 cin.getline,但它仍然给我错误的输入信息。
这是为什么
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;
}
最佳答案
你应该放置 std::getline(std::cin, cookieType);里面一会儿。尝试:
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);
}
实际上,do{}while 会更合适。
关于C++:字符串中的空格阻止我比较 cin 输入。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16906613/