Jet Mortola Joseph
Jet Mortola Joseph

Reputation: 131

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 B-Z that is not included to base 11, the program stops, what i want to happen is like this

enter image description here

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

Upvotes: 2

Views: 329

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

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);
...

Upvotes: 3

Related Questions