【问题标题】:C++ having cin read a return character让 cin 读取返回字符的 C++
【发布时间】:2010-09-14 02:58:30
【问题描述】:

我想知道如何使用cin,这样如果用户没有输入任何值而只是按下ENTERcin 就会将此识别为有效输入。

【问题讨论】:

  • "The C++ Programming Language" by Bjarne Stroustrup 当然认为 cin 会返回 '\n' 但我无法让它工作。我将尝试 getline 路线。

标签: c++ input return iostream cin


【解决方案1】:

你可能想试试std::getline

#include <iostream>
#include <string>

std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...

【讨论】:

    【解决方案2】:

    我发现对于用户输入std::getline 效果很好。

    您可以使用它来读取一行并丢弃它读取的内容。

    这样做的问题,

    // Read a number:
    std::cout << "Enter a number:";
    std::cin >> my_double;
    
    std::count << "Hit enter to continue:";
    std::cin >> throwaway_char;
    // Hmmmm, does this work?
    

    是如果用户输入其他垃圾,例如“4.5 - about”在打印下一次他需要看到的提示之前,很容易不同步并阅读用户上次写的内容。

    如果您使用std::getline( std::cin, a_string ) 读取每一行完整的内容,然后解析返回的字符串(例如使用 istringstream 或其他技术),那么即使在面对乱码输入。

    【讨论】:

      【解决方案3】:

      cin.getline 能解决您的问题吗?

      【讨论】:

        【解决方案4】:

        检测用户按下 Enter 键而不是输入整数:

        char c;
        int num;
        
        cin.get(c);               // get a single character
        if (c == 10) return 0;    // 10 = ascii linefeed (Enter Key) so exit
        else cin.putback(c);      // else put the character back
        cin >> num;               // get user input as expected
        

        或者:

        char c;
        int num;
        c = cin.peek();           // read next character without extracting it
        if (c == '\n') return 0;  // linefeed (Enter Key) so exit
        cin >> num;               // get user input as expected
        

        【讨论】:

          【解决方案5】:

          尝试取消缓冲 cin(默认为缓冲)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-12-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-06-28
            • 1970-01-01
            相关资源
            最近更新 更多