Using C++ Write a program that accepts input from the keyboard (with the input t
ID: 3847647 • Letter: U
Question
Using C++ Write a program that accepts input from the keyboard (with the input terminated by pressing the Enter key) and counts the number of letters (A-Z and az), numerical digits (0-9), and other characters. Input the string using cin and use the following looping structure to examine each character in the string with an "if" statement and multiple "else if" statements. char s[50]; int i; . . . i = 0; while (s[i] != 0) { // a string is terminated with a null (0) value . . . i++; } Your program should make use of the relational operators (e.g., == < > <= >= !=) to determine whether a particular character is a letter, number, or other character. You may only #include and may not use any other include files.
Explanation / Answer
C++ code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string input;
cout << "Enter the input string!" << endl;
cin >> input;
int alpha = 0;
int digit = 0;
int others = 0;
for (int i = 0; i < input.size(); ++i)
{
if( (48 <= (int) input[i]) and (57>=(int) input[i]) )
{
digit++;
}
else if((65 <= (int) input[i]) and (90>=(int) input[i]) or ((97 <= (int) input[i]) and (122>=(int) input[i])) )
{
alpha++;
}
else
{
others++;
}
}
cout << "The input contains " << alpha << " alphabetical characters!" << endl;
cout << "The input contains " << digit << " numeric characters!" << endl;
cout << "The input contains " << others << " other characters!" << endl;
return 0;
}
Sample Output:
Enter the input string!
akashBaviskar12345$%^
The input contains 13 alphabetical characters!
The input contains 5 numeric characters!
The input contains 3 other characters!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.