简体   繁体   中英

Conversion from base 11 to 10 c++

This code can convert from base 11 to base 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;
}

But when i enter BZ that is not included to base 11, the program stops, what i want to happen is like this

在此处输入图片说明

if the user enters invalid variables, the program should say "Invalid Input". please help

You can use 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);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM