【问题标题】:C++: Spaces in strings prevent me from comparing cin input.C++:字符串中的空格使我无法比较 cin 输入。
【发布时间】: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.getlinestd::getline 大不相同。
  • 啊,这似乎正是我在四处寻找时会忽略的事情。介意解释一下,以及我需要改变什么?
  • std::cin.getline 用于 C 字符串,坦率地说永远不要使用。 std::getline 调整输入的长度并与漂亮的 std::string 配合使用。

标签: c++ string getline spaces cin


【解决方案1】:

你应该放置 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 会更合适。

【讨论】:

  • 那行得通……有点。一旦我输入,比如说“巧克力片”,它就可以工作,但由于某种原因,它告诉我我在输入任何内容之前就输入了错误的数据。你知道为什么会这样吗?我的意思是,我有一个 std::getline(std::cin, cookieType);在它进入while循环之前,所以似乎没有理由在我输入任何内容之前显示错误消息。
  • @EvanJohnson:可能是因为您调用 get_cookie_type() 已经在缓冲区中有东西了吗?尝试输出 cookieType 的值,例如with cout
【解决方案2】:

在 while 循环中使用 std::getline(std::cin, cookieType)operator&gt;&gt; 将停在第一个空格处,而 std::getline 默认停在换行符处。

您的输入流中似乎还有字符。在第一次调用 std::getline 之前添加以下行(并包含 &lt;limits&gt; 标头):

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多