Skip to content

Instantly share code, notes, and snippets.

@ramachandrajr
Created June 2, 2017 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramachandrajr/59d27a418f44defe984b926d64511dc3 to your computer and use it in GitHub Desktop.
Save ramachandrajr/59d27a418f44defe984b926d64511dc3 to your computer and use it in GitHub Desktop.
This piece of code converts string text to integer.
#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