【发布时间】:2013-05-30 04:28:54
【问题描述】:
(对不起,我知道这个问题之前已经被问过[并回答],但没有一个解决方案对我有用,因为我的代码设置方式有些问题,我不知道那是哪一部分) .
好的,我有一个函数,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;
}
【问题讨论】:
-
cin.getline与std::getline大不相同。 -
啊,这似乎正是我在四处寻找时会忽略的事情。介意解释一下,以及我需要改变什么?
-
std::cin.getline用于 C 字符串,坦率地说永远不要使用。std::getline调整输入的长度并与漂亮的std::string配合使用。
标签: c++ string getline spaces cin