用户输入(cin) - 默认值 [英] User input(cin) - Default value

查看:199
本文介绍了用户输入(cin) - 默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在要求用户输入时使用默认值。我想用户只能按Enter键并获得默认值。考虑下面的代码,你能帮助我吗?

I can't figure out how to use a "default value" when asking the user for input. I want the user to be able to just press Enter and get the default value. Consider the following piece of code, can you help me?

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 将给定的字符串转换为数字。

Use std::getline to read a line of text from std::cin. If the line is empty, use your default value. Otherwise, use a std::istringstream to convert the given string to a number. If this conversion fails, the default value will be used.

以下是一个示例程序:

#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;
}

这篇关于用户输入(cin) - 默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆