You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.5 KiB
C++
53 lines
1.5 KiB
C++
#include <cctype> // for isdigit()
|
|
#include <cmath> // for pow()
|
|
#include <iostream>
|
|
#include <stack>
|
|
#include <string>
|
|
|
|
using namespace std;
|
|
|
|
int convert(const string &s) {
|
|
string split_string = s;
|
|
stack<int> digits;
|
|
int conversion = 0;
|
|
auto it_s = s.begin();
|
|
|
|
for (;(*it_s == ' ') && (it_s != s.end()); it_s++); // skip all spaces
|
|
for (;(isdigit(*it_s)) && (it_s != s.end()); it_s++) {
|
|
digits.push((int) *it_s - (int) '0'); // put all decimal digits onto the stack
|
|
};
|
|
if(it_s == s.end() || *it_s == ' ') {
|
|
for (int i = 0; !(digits.empty()); i++) {
|
|
conversion += digits.top() * pow(10, i);
|
|
digits.pop();
|
|
}
|
|
} else {
|
|
// throw std::invalid_argument(s + " is not a correct int representation.");
|
|
// is what I'd like to do, but I guess I couldn't return -1 then, right?
|
|
cout << s + " is not a correct non-negative int representation." << endl;
|
|
return -1;
|
|
}
|
|
return conversion;
|
|
}
|
|
|
|
void use_convert_function(const string &s) {
|
|
cout << s << " : " << convert(s) << endl << endl;
|
|
}
|
|
|
|
void test_convert_function() {
|
|
use_convert_function("0");
|
|
use_convert_function("128");
|
|
use_convert_function("+128");
|
|
use_convert_function("12x128");
|
|
use_convert_function("128 + x");
|
|
use_convert_function("128 Punkte");
|
|
}
|
|
|
|
int main() {
|
|
string s = "";
|
|
cout << "Please input a number: " << endl;
|
|
getline(cin, s);
|
|
use_convert_function(s);
|
|
return 0;
|
|
}
|