C++ having cin read a return character

前端 未结 5 1180
走了就别回头了
走了就别回头了 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:03

    I find that for user input std::getline works very well.

    You can use it to read a line and just discard what it reads.

    The problem with doing things like this,

    // 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?
    

    is that if the user enters other garbage e.g. "4.5 - about" it is all too easy to get out of sync and to read what the user wrote the last time before printing the prompt that he needs to see the next time.

    If you read every complete line with std::getline( std::cin, a_string ) and then parse the returned string (e.g. using an istringstream or other technique) it is much easier to keep the printed prompts in sync with reading from std::cin, even in the face of garbled input.

提交回复
热议问题