C++ having cin read a return character

前端 未结 5 1168
走了就别回头了
走了就别回头了 2021-02-07 20:17

I was wondering how to use cin so that if the user does not enter in any value and just pushes ENTER that cin will recognize this as valid

5条回答
  •  无人共我
    2021-02-07 21:15

    To detect the user pressing the Enter Key rather than entering an integer:

    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
    

    Alternatively:

    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
    

提交回复
热议问题