Answer to Question #288164 in C++ for Nica

Question #288164

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.

1
Expert's answer
2022-01-17T08:24:56-0500
#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!";
	}	
}

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