我想知道如何使用cin
,使得如果用户没有输入任何值,只是按下了ENTER
,cin
也能将其识别为有效的输入。
你可能希望尝试使用 std::getline
:
#include <iostream>
#include <string>
std::string line;
std::getline( std::cin, line );
if( line.empty() ) ...
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?
std::getline(std::cin, a_string)
读取每一行完整的字符串,然后解析返回的字符串(例如使用istringstream或其他技术),即使面对混乱的输入,也更容易将打印的提示与从std::cin中读取的内容保持同步。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
尝试取消缓冲cin(它默认为缓冲)。