I would put the numerical representation of the number into an std::string. From here you can access each digit separately:
std::string number = "123";
std::cout << number[0]; //outputs '1'
You would then have to have a giant switch statement to convert a '1' to "one", etc.
Hope this helps,
Dave
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
Google it. I bet the generic algorithm for this has been done many times before.
If you're only using three digits max it shouldn't be too hard.
For example the following looks like a useful template, written in java though.
http://www.rgagnon.com/javadetails/java-0426.html
#include <iostream>
#include <string>
#include <climits>
class Foo
{
public:
std::string bar(int number)
{
std::string tensNames[] = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
std::string numNames[] = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
std::string soFar;
if (number % 100 < 20)
{
soFar = numNames[number % 100];
number /= 100;
}
else
{
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar + "\n";
return numNames[number] + " hundred" + soFar + "\n";
}
};
int main()
{
Foo bar;
std::cout << bar.bar(125);
std::cout << bar.bar(9);
std::cout << bar.bar(1);
std::cout << bar.bar(200);
std::cout << bar.bar(999);
std::cin.get();
}
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
If its only 1-3 length, then just hard code it like so :
int toInt(const string& str){
int result = 0;
switch(str.length()){
case 1: result = str[0] - '0'; break;
case 2: result = (str[0]-'0')*10 + (str[1] - '0'); break;
case 3: result = (str[0]-'0')*100 + (str[1] - '0')*10 + (str[2] - '0'); break;
default: /* not supported */ break;
}
return result;
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
firstPerson - what is this supposed to do? Convert a string to an int? Shouldn't he just use a std::stringstream?
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
firstPerson - what is this supposed to do? Convert a string to an int? Shouldn't he just use a std::stringstream?
sorry misread his post.
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608