write a C++ program, 1. reads each character from a user input, extracts the cha
ID: 3926359 • Letter: W
Question
write a C++ program,
1. reads each character from a user input, extracts the character if it is a digit, and calculates the sum of all the digits.
2. The program stops reading the user input when the new line character ‘ ’ is encountered. For the output of the program, you should print each digit extracted from the user input and the sum of all the digits.
**USE:
cin.get(c) // extracts a single character from the standard input stream (cin)
// c is a char type variable where the extracted value is stored
**the output looks like:
Thank you very much!!!
Enter any texts: qlw2e3r4t5y6u7i809po 1234567890Explanation / Answer
#include <stdio.h>
void main()
{
char string[80];
int count, nc = 0, sum = 0;
printf("Enter the string containing both digits and alphabet ");
scanf("%s", string);
for (count = 0; string[count] != ''; count++)
{
if ((string[count] >= '0') && (string[count] <= '9'))
{
nc += 1;
sum += (string[count] - '0');
}
}
printf("NO. of Digits in the string = %d ", nc);
printf("Sum of all digits = %d ", sum);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.