Write a program that reads digits and composes them into integers. For example, 123 is read
as the characters 1, 2, and 3. The program should output 123 is 1 hundred and 2 tens and 3
ones. The number should be output as an int value. Handle numbers with one, two, three, or
four digits. Hint: To get the integer value 5 from the character '5' subtract '0', that is, '5'–
'0'==5.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char c;
cout<<"Please, enter int number (max 4 digits): ";
int i;
string strnum;
for(i=0;i<=4;i++)
{
c=getchar();
if(!isdigit(c))break;
strnum+=c;
}
cout<<strnum<<" is ";
int num;
if(strnum.size()==1)
{
num=strnum[0]-'0';
cout<<num;
}
else if(strnum.size()==2)
{
num=strnum[0]-'0';
if(num==1)
cout<<num<<" ten and ";
else
cout<<num<<" tens and ";
num=strnum[1]-'0';
cout<<num;
}
else if(strnum.size()==3)
{
num=strnum[0]-'0';
if(num==1)
cout<<num<<" hundred and ";
else
cout<<num<<" hundreds and ";
num=strnum[1]-'0';
if(num==1)
cout<<num<<" ten and ";
else
cout<<num<<" tens and ";
num=strnum[2]-'0';
cout<<num;
}
else if(strnum.size()==4)
{
num=strnum[0]-'0';
if(num==1)
cout<<num<<" thousand and ";
else
cout<<num<<" thousands and ";
num=strnum[1]-'0';
if(num==1)
cout<<num<<" hundred and ";
else
cout<<num<<" hundreds and ";
num=strnum[2]-'0';
if(num==1)
cout<<num<<" ten and ";
else
cout<<num<<" tens and ";
num=strnum[3]-'0';
cout<<num;
}
else
{
cout<<"Undefined input!";
}
}
Comments
Leave a comment