当询问用户输入时,我不知道如何使用“默认值”。我希望用户能够只按Enter并获取默认值。考虑下面的代码,您能帮我吗?

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;

最佳答案

使用 std::getline std::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;
}

关于c++ - 用户输入(cin)-默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10314682/

10-11 22:46
查看更多