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
|
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void print_thousands(ostream& out, unsigned n) {
static const char
*ones[] {
"", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
},
*tens[] {
"", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
if (n > 99) out << ones[n / 100] << " hundred ";
n %= 100;
if (n > 19) {
out << tens[n / 10] << ' ';
n %= 10;
}
if (n > 0) out << ones[n] << ' ';
}
void number_to_words(ostream& out, unsigned long long n, int mag = 0) {
static const char* thous[] {
"", "thousand", "million", "billion", "trillion",
"quadrillion", "quintillion"
};
if (n == 0) {
if (mag == 0) out << "zero";
}
else {
number_to_words(out, n / 1000, mag + 1);
print_thousands(out, n % 1000);
if (n % 1000 && mag) out << thous[mag] << ' ';
}
}
void number_to_words(ostream& out, long long n) {
if (n < 0) {
out << "negative ";
n = -n;
}
number_to_words(out, (unsigned long long)n);
}
int main()
{
long long n;
while (cout << ">> ", cin >> n) {
ostringstream out;
number_to_words(out, n); // or pass cout if you don't need a string
cout << out.str() << '\n';
}
cout << '\n';
}
|