C++:字符串中的空格阻止我比较 cin 输入。

标签 c++ string getline spaces cin

(抱歉,我知道这个问题之前有人问过 [并回答过],但没有一个解决方案对我有用,因为我的代码设置方式有点不稳定,我不知道那是哪一部分) .

好的,我有一个函数 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/

相关文章:

c# - 是否有任何免费的 C++ 和/或 C# 编译器可以在支持 Android 的平板电脑上运行?

Java Netbeans : Splitting a string using regular expressions

C++ 为什么 getline() 结束 while 循环?

c++ - 如何让字符串输入n次?

C++ 读/写文本文件问题

c++ - 如何在 Linux 中反汇编二进制可执行文件以获取汇编代码?

c++ - 从 MATLAB 生成代码后,在 C++ 中将 vector<> 转换为 emxArray_real_T

c++ - 编译 Qt 教程时出现 "undefined symbols for architecture"链接器错误

c - C语言输出中倒置的问号是什么意思?

vb.net - 获取其他字符串之间的字符串 vb.net