此代码可以从基数 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时,程序停止,我想要发生的事情是这样的
如果用户输入无效变量,程序应显示“无效输入”。请帮忙
最佳答案
您可以使用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/