C++ having cin read a return character

末鹿安然 提交于 2019-12-04 10:27:39

问题


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 input.


回答1:


You will probably want to try std::getline:

#include <iostream>
#include <string>

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



回答2:


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.




回答3:


Does cin.getline solve your problem?




回答4:


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



回答5:


Try unbuffering cin (it's buffered by default).



来源:https://stackoverflow.com/questions/150726/c-having-cin-read-a-return-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!