In: Computer Science
Create a C++ program that will prompt the user to input an integer number and output the corresponding number to its numerical words. (From 0-1000000 only)
**Please only use #include <iostream>, switch and if-else statements only and do not use string storing for the conversion in words. Thank you.**
**Our class is still discussing on the basics of programming. Please focus only on the basics. Thank you.**
Example outputs:
Enter a number: 68954
Sixty Eight Thousand Nine Hundred Fifty Four
Enter a number: 100000
One Hundred Thousand
Enter a number: -2
Number should be from 0-1000000 only
#include<iostream.h>
void main()
{
/* code */
char num[100];
char *sindig[] = { "zero", "one", "two","three",
"four","five","six", "seven", "eight", "nine"};
char *twodig[] = {"", "ten", "eleven",
"twelve","thirteen", "fourteen","fifteen", "sixteen","seventeen",
"eighteen", "nineteen"};
char *tensmultiple[] = {"", "", "twenty", "thirty",
"forty", "fifty","sixty", "seventy", "eighty", "ninety"};
char *tenspower[] = {"hundred", "thousand"};
cout<<"Enter a number:";
cin>>num;
int len = strlen(num);
if(num>1000000 || nun<0)
cout<<"Number should be from
0-1000000 only";
printf("\n%s: ", num);
/* For single digit number */
if (len == 1) {
printf("%s\n", sindig[*num - '0']);
return;
}
/* Iterate while num is not '\0' */
while (*num != '\0') {
/* Code path for first 2 digits */
if (len >= 3) {
if (*num -'0' != 0) {
printf("%s ", sindig[*num - '0']);
printf("%s ", tensmultiple[len-3]); // here len can be 3 or 4
}
--len;
}
/* Code path for last 2 digits */
else {
/* Need to explicitly handle 10-19. Sum of the two digits is
used as index of "twodig" array of strings */
if (*num == '1') {
int sum = *num - '0' + *(num + 1)- '0';
printf("%s\n", twodig[sum]);
return;
}
/* Need to explicitely handle 20 */
else if (*num == '2' && *(num + 1) == '0') {
printf("twenty\n");
return;
}
/* Rest of the two digit numbers i.e., 21 to 99 */
else {
int i = *num - '0';
printf("%s ", i? tensmultiple[i]: "");
++num;
if (*num != '0')
printf("%s ", sindig[*num - '0']);
}
}
++num;
}
}
}
sample input output:
Enter a number: 68954
Sixty Eight Thousand Nine Hundred Fifty Four