I haven't fully tested this but you made one small blooper:
1 2 3
while (ch != '#')
{
str += ch; // <--
nter characters. Press # to stop.
aBraD123a4eA#
The total number of characters is 12
Uppercase letters: 3
Lowercase letters: 5
Digits: 4
Program ended with exit code: 0
Hi Joe9583, and welcome.
If you would do us a favor when you post; select all the code portion of the text and hit the button to the right that looks like this: <>
That plus a little formatting will make it easier to read your code.
You don't need to use str to get the total number if chars - just increment your existing total variable. Also, the loop can be improved so that you have only one cin.get(), not two.
#include <cctype> // <--- For "std::tolower() and std::toupper()" + others. Added. Should be included even if you do not seam to need it.
#include<iostream>
#include<string>
usingnamespace std;
int main()
{
string str;
char ch{};
int uppercount{}, lowercount{}, digits{}, total{}, length{}, spaces{}, others{};
cout << "Enter characters. Press # to stop." << '\n';
cin.get(ch);
while (ch != '#')
{
str += ch; // <--- Added.
if (isupper(ch))
uppercount++;
elseif (islower(ch))
lowercount++;
elseif (isdigit(ch))
digits++;
elseif (ch == ' ')
spaces++;
else
others++;
cin.get(); // <--- Eats the "\n" so it is not stored in the string. Use if you enter 1 letter at a time.
cin.get(ch); // <--- Gets next character from keyboard.
}
length = str.length(); // <--- Could do without this line and variable.
cout
<< "\nThe total number of characters is " << length << '\n' // <--- Or replace "length" with "str.length()" or ".size()" Retuens the same number.
<< "Uppercase letters: " << uppercount << '\n'
<< "Lowercase letters: " << lowercount << '\n'
<< "Digits: " << digits << '\n'
<< "Others: " << others << '\n'; // <--- Added.
return 0;
}
In lines 10 and 11 it is a good idea to initialize ALL your variables. That way you at least know that they do not contain a garbage value.
You have created "str", but never put anything into it then expect to have something greater than (0)zero at line 35. Line 18 takes care of this problem.
The while loop is fine although I did have to add line 31. This line does not work if you would enter a whole string ending in "#" and Enter.
int uppercount = 0, lowercount = 0, digits = 0, total = 0, length, spaces = 0, others = 0;
@OP the above line you wrote is an acceptable way of initializing the variables.
In fact, by initializing ch to char ch= '?' or with some other convenient (sentinel) value in your program you can simply delete your first cin.getch() line and relocate the second one from where it is to directly after the while statement.