1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
#include <iostream>
#include <string>
const std::string units[] = {
"", // not used, but keeps words at their index
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven", // not one-teen
"twelve", // not two-teen
"thirteen", // not three-teen
"fourteen",
"fifteen", // not five-teen
"sixteen",
"seventeen",
"eighteen", // not eight-teen
"nineteen",
};
// Danish would need an entirely different lookup table
// http://www.olestig.dk/dansk/numbers.html
const std::string tens[] = {
"?!", // If these appear, it means that the code
"??", // to isolate the units broke.
"twenty",
"thirty",
"forty", // not fourty
"fifty", // not fivety
"sixty",
"seventy",
"eighty", // not eightty
"ninety",
};
std::string toWords(int n) {
std::string result;
if ( n < 20 ) {
result = units[n];
} else {
result = tens[n/10];
if ( n % 10 != 0 ) {
result += " ";
result += units[n%10];
}
}
return result;
}
int main() {
std::cout<<"Enter a digit from 1-3000: ";
int num;
std::cin>>num;
if (1<=num && num<=3000)
{
int t=(num/1000)%10;
int h=(num/100)%10;
int u=num%100;
std::string answer;
if ( t > 0 ) {
answer = toWords(t) + " thousand";
}
if ( h > 0 ) {
if ( t > 0 ) answer += ", ";
answer += toWords(h) + " hundred";
}
if ( u > 0 ) {
if ( t > 0 || h > 0 ) answer += " and ";
answer += toWords(u);
}
std::cout << answer << std::endl;
}
}
|