C++ code Write a program to ask the user to enter a string. The string can be of
ID: 3582031 • Letter: C
Question
C++ code
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>
#include <string>
using namespace std;
void countDetails(string s){
int digitCount = 0, charCount = 0, specialCount = 0;
for(int i=0; i<s.length(); i++){
if((s[i] >= 'a' && s[i] <='z') || (s[i] >= 'A' && s[i] <='Z')){
charCount++;
}
else if(s[i] >='0' && s[i]<='9'){
digitCount++;
}
else{
specialCount++;
}
}
cout<<"Number of digits: "<<digitCount<<endl;
cout<<"Number of characters: "<<charCount<<endl;
cout<<"Number of special characters: "<<specialCount<<endl;
}
int main()
{
string s;
cout << "Enter the string: ";
getline(cin ,s);
countDetails(s);
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter the string: Suresh Murapaka E825156 !@12#$
Number of digits: 8
Number of characters: 15
Number of special characters: 7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.