Hello,
I am new to c++. I have been trying to write a program that counts the total number of characters in a string. The program then outputs the total of letters, total of numerical characters, and total of other characters. The program will not count numbers or other characters but it will count the letters fine. Any help would be greatly appreciated. This is the source code:
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
char s[50];
int i;
int letters = 0; // letters
int numbers = 0; // numerical characters
int other = 0; // other characters
int total; // total of all characters
cout << "Enter a continuous string of characters with no blank spaces" << endl;
cout << "(example: aBc1234!@#$%)" << endl;
cout << endl;
cout << "Enter your string:";
cin >> s;
cout << endl;
//loop through the string, counting numbers, letters & others
////////////////////////////////////////////////////////////////////
//count other characters
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
//calculate total of characters
////////////////////////////////////////////////////////////////////
total = letters + numbers + other;
////////////////////////////////////////////////////////////////////
//output the results
////////////////////////////////////////////////////////////////////
cout << "Your string has " << total << " total characters" << endl;
cout << letters << " letters " << endl;
cout << numbers << " numerical characters " << endl;
cout << other << " other characters " << endl;
One thing is that you use the >> operator for input. Doing so, you are limited to stop your input when the first space character (space, tab, newline etc...) is encountered. Use cin.getline(s,50,'\n'); instead.
Another thing is that you only increase i when you encounter a letter, while it should be increased every time. Also, in the way you do it you don't take care of every possible character. I suggest something like this:
1 2 3 4 5 6 7 8 9 10
while (s[i]!=0)
{
if (/*is letter*/) letters++;
elseif (/*is number*/) numbers++;
else other++; //anything else than letters and numbers
i++; //don't forget this!
}
Finally, don't forget the c-library functions isalpha, isdigit, etc..., found in <cctype>: