In: Computer Science
Write a C++ program that asks the user to enter a series
of
single-digit numbers with nothing separating them. Read the
input
as a C-string or a string object. The program should display
the
sum of all the single-digit numbers in the string. For example,
if
the user enters 2514, the program should display 12, which is
the
sum of 2, 5, 1, and 4. The program should also display the
highest
and lowest digits in the string.
It is recommended that you include a function such as int charToInt(char)
The charToInt function
accepts a char and returns the char's value as an integer digit.
If
the char is not a digit, the function returns 0.
Remember to use proper formatting and code documentation.
Sample screen output (user input is in bold) :
Enter a series of digits with no spaces between them. 1 2 3 4 5 Incorrect input....? Enter a series of digits with no spaces between them. 1234 4321 Incorrect input....? Enter a series of digits with no spaces between them. 1234 srjc Incorrect input....? Enter a series of digits with no spaces between them. srjc 1234 Incorrect input....? Enter a series of digits with no spaces between them. 987654321 The sum of those digits is 45 The highest digit is 9 The lowest digit is 1 Process returned 0 (0x0) execution time : 71.074 s Press any key to continue.
Solution:
Look at the code and comments for better understanding............
Screenshot of the code:
Output:
Code to copy:
#include<iostream>
using namespace std;
//a function that checks if the input is valid or not
bool check(string input)
{
for(int i=0;input[i]!='\0';i++)
{
//if the input contains spaces or characters other than digits we return false
if(input[i]==' ' || input[i]<'0' || input[i]>'9')
{
return false;
}
}
return true;
}
//converting a char to digit
int charToInt(char ch)
{
return ch-'0';
}
int main()
{
//loop untill a valid input is given
while(1)
{
string input;
cout<<"Enter a series of digits with no spaces between them."<<endl;
getline(cin,input);
//check the input
if(check(input)==false)
{
cout<<"Incorrect input....?"<<endl<<endl;
continue;
}
int sum=0,low=9,high=0;
for(int i=0;input[i]!='\0';i++)
{
int digit = charToInt(input[i]);
//finding sum , lowest and highest digit
sum += digit;
if(digit < low)
low = digit;
if(digit > high)
high = digit;
}
//printing the digits
cout<<"The sum of those digits is "<< sum << endl;
cout<<"The highest digit is "<< high << endl;
cout<<"The lowest digit is "<< low << endl;
break;
}
}
I hope this would help................................:-))