Answer to Question #295338 in C++ for hussnain

Question #295338

program to convert 6 digits numbers into words


1
Expert's answer
2022-02-08T15:18:38-0500
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;


string num3(int x) {
    string s0[] = {"zero", "one", "two", "three", "four",
                   "five", "six", "seven", "eight", "nine",
                   "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen",
                   "seventeen", "eighteen", "nineteen"};
    string s20[] = {"twenty", "thirty", "fourty", "fifty",
                    "sixty", "seventy", "eighty", "ninty"};
    string res = "";
    int c = x/100;
    if (c>0) {
        res = s0[c] + " handred";
        if (c > 1) 
            res += "s";
    }


    x %= 100;
    if (x < 20) {
        if (res.length() != 0)
            res += " ";
        res += s0[x];
    }
    else {
        int t = x/10;
        x %= 10;
        if (res.length() != 0)
            res += " ";
        res += s20[t-2];
        
        if (x > 0) {
            res += " " + s0[x];
        }
    }
    return res;
}


string num2str(int x) {
    string res="";


    if (x==0) {
        return "zero";
    }


    if (x < 0) {
        res = "negative ";
        x = -x;
    }


    int th = x / 1000;
    x %= 1000;
    if (th > 1) {
        if (res.length() != 0)
            res += " ";
        res += num3(th) + " thousands";
    }
    else if (th == 1) {
        if (res.length() != 0)
            res += " ";
        res += "one thousand";
    }


    if (res.length() != 0)
            res += " ";
    res += num3(x);
    
    return res;
}


int main() {
    int num;
    string str;


    cout << "Enter 6-digits number: ";
    cin >> num;
    if (abs(num) >= 1000000) {
        cout << "The number is too big" << endl;
        exit(1);
    }


    str = num2str(num);
    cout << str << endl;


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog