Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Convert Number to Text using C++11

#include <iostream>
#include <string>
#include <vector>

using namespace std;

std::string number_to_text(int number)
{
    std::vector<std::string> ones{"", "one", "two", "three", "four", "five","six", "seven", "eight", "nine"};
    
    std::vector<std::string> tens{"", "ten", "twenty", "thirty",
        "fourty", "fifty", "sixty", "seventy", "eight", "ninety"};
        
    std::vector<std::string> hundreds{"", "one hundred", "two hundred",
        "three hundred", "four hundred", "five hundred", "six hundred",
        "seven hundred", "eight hundred", "nine hundred"};
        
    std::vector<std::string> thousands{"", "one thousand", "two thousand",
        "three thousand", "four thousand", "five thousand",
        "six thousand", "seven thousand", "eight thousand",
        "nine thousand"};
        
    std::vector<std::vector<std::string>> map;
        
    std::string text;
        
    map.push_back(ones);
    map.push_back(tens);
    map.push_back(hundreds);
    map.push_back(thousands);
    
    int step = 0;
    
    while (number > 0)
    {
        int digit = number % 10;
        number = number / 10;
        
        text.insert(0, " ");
        text.insert(0, map.at(step).at(digit));
        
        step = step + 1;
    }
    
    text.pop_back();
    return text;
}

int main()
{
   std::cout << number_to_text(1972) << std::endl;
   std::cout << number_to_text(1970) << std::endl;
   std::cout << number_to_text(1900) << std::endl;
   std::cout << number_to_text(1000) << std::endl;
   
   return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.