2012-04-25 120 views
4

我不知道如何在询问用户输入时如何使用“默认值”。我希望用户能够按Enter键并获取默认值。考虑下面的一段代码,你能帮助我吗?用户输入(cin) - 默认值

int number; 
cout << "Please give a number [default = 20]: "; 
cin >> number; 

if(???) { 
// The user hasn't given any input, he/she has just 
// pressed Enter 
number = 20; 

} 
while(!cin) { 

// Error handling goes here 
// ... 
} 
cout << "The number is: " << number << endl; 

回答

9

使用std::getlinestd::cin阅读的文本行。如果该行为空,请使用您的默认值。否则,请使用std::istringstream将给定的字符串转换为数字。如果此转换失败,将使用默认值。

下面是一个示例程序:

#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

int main() 
{ 
    std::cout << "Please give a number [default = 20]: "; 

    int number = 20; 
    std::string input; 
    std::getline(std::cin, input); 
    if (!input.empty()) { 
     std::istringstream stream(input); 
     stream >> number; 
    } 

    std::cout << number; 
} 
+0

是否有任何方法来检查用户是否输入有效的输入(如在cin中)。 我的意思是,我想要检测用户输入某些字符而不是数字并输出错误信息。 – tumchaaditya 2012-04-26 02:44:36

0
if(!cin) 
    cout << "No number was given."; 
else 
    cout << "Number " << cin << " was given."; 
0

我会忍不住用getline()读取线为一个字符串,那么你(可以说)在转换过程中加以控制:

int number(20); 
string numStr; 
cout << "Please give a number [default = " << number << "]: "; 
getline(cin, numStr); 
number = (numStr.empty()) ? number : strtol(numStr.c_str(), NULL, 0); 
cout << number << endl; 
7

这可以作为接受答案的替代方法。我会说std::getline在矫枉过正的一面。

#include <iostream> 

int main() { 
    int number = 0; 

    if (std::cin.peek() == '\n') { //check if next character is newline 
     number = 20; //and assign the default 
    } else if (!(std::cin >> number)) { //be sure to handle invalid input 
     std::cout << "Invalid input.\n"; 
     //error handling 
    } 

    std::cout << "Number: " << number << '\n';  
} 

这里有一个live sample有三个不同的运行和输入。

+0

对于它的价值,我同意 - 我喜欢你的版本比我的更好。 – 2015-08-26 15:08:10