【问题标题】:How can I print the integer taken as input without spaces? [closed]如何打印没有空格作为输入的整数? [关闭]
【发布时间】:2018-10-12 13:01:35
【问题描述】:

我想把用户输入的数字作为一个整体打印出来,想忽略空格。

像这样:

int aValue;
cin >> aValue;

这里假设用户输入49 506,我想打印成49506

【问题讨论】:

标签: c++ c++14


【解决方案1】:

首先你需要从用户那里得到一个带空格的字符串,注意你需要使用std::getline(),因为operator>>不接受空格:

std::string str;
std::getline( cin, str );

然后你使用std::remove_if()std::isspace() 从你的字符串中删除空格:

auto it = std::remove_if( str.begin(), str.end(), []( unsigned char c ) { return std::isspace(c); } );
str.erase( it, str.end() );

然后您使用std::stoi() 将您的字符串转换为int

auto aValue = std::stoi( str );

您还应该将错误检查添加到您的代码处理错误条件中,如文档中所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2021-07-25
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2015-05-19
    • 2023-03-10
    相关资源
    最近更新 更多