My teacher wants us to write a program that counts the number of letters (A-Z, a-z), numbers, and special characters in an input string. We are only allowed to use <iostream>.
My program counts the letters and numbers correctly, but I can't get a correct count of other characters. This is what happens: Enter your string: aBc1234!@#$% Your string has 3 letters 4 numbers, and 4 other characters. It should show 5 characters. Here is my code:
#include <iostream> //preprocessor directive
using namespace std;
//preprocessor directives
int main ()
{
//declare and initialize variables
char s[50];
int i;
int letter = 0;
int number = 0;
int other = 0;
//user input
cout << "Enter a continuous string of characters with no blank spaces" << endl;
cout << "(example: aBc1234!@#$%)" << endl << endl;
cout << "Enter your string: ";
cin >> s;
cout <<endl;
//loop through the string
//count letters
i = 0;
while (s[i] !=0)
{
if ((s[i] >= 'a' && s[i] <= 'z') ||
(s[i] >= 'A' && s[i] <= 'Z'))
letter++;
i++;
}
//count numbers
i = 0;
while (s[i] !=0)
{
if ((s[i] >= '0' && s[i] <= '9'))
number++;
i++;
}
//count other
i = 0;
while (s[i] !=0)
{
if ((s[i] >= '!' && s[i] <= ')'))
other++;
i++;
}
//output results
cout << "Your string has " << letter << " letters" << endl;
cout << number << " numbers, and " << endl;
cout << other << " other characters" << endl;
Because you are doing your if statement wrong: if ((s[i] >= '!' && s[i] <= ')'))
If you print out the integer values (which is what that if statement is comparing) you would see that the problem (some of the symbols are out of range of your comparison):
Enter your string: !@#$%^&*()_+
! : 33
@ : 64
# : 35
$ : 36
% : 37
^ : 94
& : 38
* : 42
( : 40
) : 41
_ : 95
+ : 43
Your string has 0 letters
0 numbers, and
7 other characters
Your comparison translates to if s[i] is greater than or equal to 33 AND s[i] is less than or equal to 41 then increment other, but @ is 64 ^ is 94 _ is 95. You need to find what the int values are or find the symbols that are the highest and lowest values to plug them in, but then you will still have to tweak it because they aren't linear and jump around for special characters as shown by this chart: http://web.cs.mun.ca/~michael/c/ascii-table.html
Here is the full code, but test it out to make sure. You had the right idea. Turned your while loop into one loop rather than three as you can do all that in one pretty easy.
You are welcome, but make sure you take note of my changes as I edited the code after you replied. The while loop only needed to be one rather than three.