c++ - 从基数 11 到 10 c++ 的转换

标签 c++ string

此代码可以从基数 11 转换为基数 10:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str;
    cout <<"CONVERSION\n\n";
    cout <<"Base 11 to Decimal\n";
    cout << "Base 11: ";
    getline (std::cin,str);
    unsigned long ul = std::stoul (str,nullptr,11);
    cout << "Decimal: " << ul << '\n';
    return 0;
}

但是当我输入不包含在基数11中的B-Z时,程序停止,我想要发生的事情是这样的

enter image description here

如果用户输入无效变量,程序应显示“无效输入”。请帮忙

最佳答案

您可以使用std::string::find_first_not_of

...
getline (std::cin,str);
const auto bad_loc = str.find_first_not_of("0123456789aA");
if(bad_loc != std::string::npos) {
  throw "bad input"; // or whatever handling
}
unsigned long ul = std::stoul (str,nullptr,11);
...

关于c++ - 从基数 11 到 10 c++ 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35739548/

相关文章:

java - `+`在Java源代码中的Strings在哪里实现?

c# - 来自字符串值的通用类型

c++ - 在方法调用中抛出堆栈溢出异常

c++ - 指针和数组问题

c++ - 为什么我的 C++ 编译器不能推导出 boost 函数的模板参数?

const char * str 问题

java - 星号字符串,屏蔽密码

c++ - const 类名 &obj == 类名 const &obj?

c++ - 重载运算符 - () 作为自由函数而不是成员函数的意义?

MYSQL - 日期/时间显示最近 30 分钟