Created
June 2, 2017 12:56
-
-
Save ramachandrajr/59d27a418f44defe984b926d64511dc3 to your computer and use it in GitHub Desktop.
This piece of code converts string text to integer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdexcept> | |
#include <cmath> | |
using namespace std; | |
/** | |
* Reports any non numeric charaters in a string. Removes if just whitespace. | |
* @param {string} str - String to convert. | |
* @return {string} String with just numbers. | |
*/ | |
string just_nums(string str) | |
{ | |
string no_spaces = ""; | |
for (int i = 0; i < str.length(); ++i) | |
{ | |
int dig = str.at(i)-48; | |
// If a space. | |
if ( dig == -16 ) | |
{} | |
// 0 - 9 | |
else if (dig > -1 && dig < 10) | |
no_spaces += str.at(i); | |
// non numeric | |
else | |
throw logic_error("There was a non character"); | |
} | |
return no_spaces; | |
} | |
/** | |
* Converts a legit number in string form to integer. | |
* @param {string} num - Number to convert to int. | |
* @return {int} Integer form of string. | |
*/ | |
int str_to_int(string num) | |
{ | |
const int LEN = num.length(); | |
int tot = 0; | |
for (int i = 0; i < LEN; ++i) | |
tot += (num.at(i)-48) * pow(10,LEN-i-1); | |
return tot; | |
} | |
int main() | |
{ | |
try | |
{ | |
// just nums first | |
string nummed = just_nums("234 "); | |
// Convert to number | |
cout << str_to_int(nummed) << endl; | |
} | |
catch (logic_error err) | |
{ | |
cerr << err.what() << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment