Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ problem Write a program to ask the user to enter a string. The string can be

ID: 3581809 • Letter: C

Question

C++ problem

Write a program to ask the user to enter a string. The string can be of any length and contain any ASCII characters (digits, alphabets, special characters, etc.). Write a void return type function to count the number of digits, the number of alphabets and the number of special characters in the string the user has entered. You need to pass to the function the string the user has entered and the function needs to display the counts on the screen. Choose either C-string or C++ string library.

Explanation / Answer

#include <iostream>
using namespace std;

void stroperations(char str[]); //We are declaring the function for doing the string operation

int main()
{
char str[350];
  

cout << "Enter a line of string: "; //Enter a string
cin.getline(str, 350);
stroperations (str); //Function Called with string as parameter
}

void stroperations (char str[]) //Function definition
{
int countDigits,countAlphabet,countSpecialChar,countSpaces;
int counter;
  
//assign all counters to zero
countDigits=countAlphabet=countSpecialChar=countSpaces=0;
  
for(counter=0;str[counter]!=0;counter++) //Running a loop for the string passed
{

if(str[counter]>='0' && str[counter]<='9') //Checking for digits
countDigits++;
else if((str[counter]>='A' && str[counter]<='Z')||(str[counter]>='a' && str[counter]<='z')) //Checking for alphabets
countAlphabet++;
else if(str[counter]==' ') //Checking for White Spaces
countSpaces++;
else
countSpecialChar++; //increamenting for Special Characters
}
  

cout << "Alphabets: " << countAlphabet << endl;
cout << "Spaces: " << countSpaces << endl;
cout << "Digits: " << countDigits << endl;
cout << "Special Char: " << countSpecialChar << endl;

  
  
}

O/P for the above code

Enter a line of string: love greenery 123 &

Alphabets: 12

Spaces: 3

Digits: 3

Special Char: 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote