Skip to content

Instantly share code, notes, and snippets.

@gmbeard
Created September 17, 2015 14:36
Show Gist options
  • Save gmbeard/91fccc48f8c2bbd63e92 to your computer and use it in GitHub Desktop.
Save gmbeard/91fccc48f8c2bbd63e92 to your computer and use it in GitHub Desktop.
Parse zero-padded number
#include <iostream>
#include <string>
#include <stdexcept>
int main(int, char *[])
{
using std::string;
using std::cin;
using std::cout;
using std::endl;
using std::runtime_error;
string input_num;
int converted_num = 0;
cout << "Enter 4 char number..." << endl;
cin >> input_num;
try {
if(input_num.size() != 4) {
throw runtime_error("Input must be 4 characters long!");
}
for(auto &&c : input_num) {
auto i = c - '0';
if(i < 0 || i > 9) {
throw runtime_error("Input must contain numbers only!");
}
converted_num = (converted_num * 10) + i;
}
cout << "Result: " << converted_num << endl;
}
catch(runtime_error &e) {
cout << e.what() << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment