Hey All,
I just finished my code and it seams to work fine. I'm looking for advice on improving it or making it easier to understand. Its not Fully complete because I only have to set up to take in a number less than 2147483648 because i am using an int. I know that can be changed, but before I get it fully polished I would appreciate your insights.
Thanks for Reading
Nathan
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int GetNumber(std::string number)
{
std::string words[31] = {"one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen","nineteen", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety","hundred", "thousand", "million", "billion"};
int numbers[31] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,30, 40, 50, 60, 70, 80, 90, 100, 1000, 1000000, 1000000000};
for (int i = 0; i < 31; i++)
{
if (number == words[i])
return numbers[i];
}
return 0;
}
int ConvertTextToNumber(std::string sentence)
{
int number = 0;
std::vector<std::string> parts;
std::string tempString;
size_t size = sentence.size();
for (size_t i = 0; i < size; i++)
{
if (sentence[i] == ' ')
{
parts.push_back(tempString);
tempString.clear();
}
else
{
tempString += sentence[i];
}
}
parts.push_back(tempString);
size = parts.size();
std::vector<std::string> formula;
formula.push_back(parts[0]);
for (size_t i = 1; i < size; i++)
{
if (parts[i] == "and")
continue;
if (parts[i] == "hundred" || parts[i] == "thousand" || parts[i] == "million" || parts[i] == "billion")
{
formula.push_back("*");
}
else
{
formula.push_back("+");
}
formula.push_back(parts[i]);
}
size = formula.size();
std::vector<int> numbers;
int tempNumber = GetNumber(formula[0]);
for (size_t i = 1; i < size; i++)
{
tempString = formula[i];
if (tempString == "*")
{
tempNumber *= GetNumber(formula[++i]);
}
if (tempString == "+")
{
tempNumber += GetNumber(formula[++i]);
}
if (formula[i] == "thousand" || formula[i] == "million" || formula[i] == "billion")
{
numbers.push_back(tempNumber);
tempNumber = 0;
}
}
numbers.push_back(tempNumber);
size = numbers.size();
for (size_t i = 0 ; i < size; i++)
{
number += numbers[i];
}
return number;
}
int main()
{
std::cout << ConvertTextToNumber("nine hundred eighty seven million six hundred fifty four thousand three hundred and twenty one");
std::cin.get();
return 0;
}