I'm having trouble with a basic c++ program assignment, and would greatly appreciate any help. The assignment is as follows:
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 a-z), 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.
My program thus far is:
#include <iostream>
using namespace std;
int main()
{
char s[50];
int i;
int numLet, numChars, otherChars = 0;
cout << "Enter a continuous string of characters" << endl;
cout << "(example: aBc1234!@#$%)" << endl;
cout << "Enter your string: ";
cin >> s;
i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))
{numLet++;
}
else if (s[i] >= 48 && s[i] <= 57)
{numChars++;
}
else if ((s[i] >= 33 && s[i] <= 4) || (s[i] >= 58 && s[i] <=64) || (s[i] >= 9 && s[i] <= 96) || (s[i] >= 123 && s[i] <= 255))
{otherChars++;
}
i++;
}
cout << numLet << " letters" << endl;
cout << numChars << " numerical characters" << endl;
cout << otherChars << " other characters" << endl;
return 0;
}
The letter count gives a value a little too low, and the number count gives a large negative number. Other chars seems to function fine.
Aucun commentaire:
Enregistrer un commentaire