Mojo Mojo - 1 month ago 4x
C++ Question

C++ beginner, switch isn't outputting first character of string

My task is to get a string with no spaces from the user and make the computer count the number of characters, letters, numbers, and special characters (i.e. !@#$%^&*) However the program seems to be skipping the first character no matter what category this character falls under. note that it does count it in the number of characters just not in its category
cin >> aZ12!@

output: 6 characters, 1 letter, 2 numbers, 2 special characters.
it always skips the first character.

#include <iostream>
#include <string>
using namespace std;

int main()
char str[100]; // available character string max is 99 characters
int i;
int lett;
int num;
int spec;

cout << "Please enter a continuous string of characters with no spaces" << endl ;
cout << "(example: ASO@23iow$)" << endl << endl ; //shows an example and then adds a blank line
cout << "Enter your string: " ;
cin >> str ;
cout << endl ;

while(str[i] != 0)
case '0' ... '9':
i++ && num++;
break ;
case 'a' ... 'z':
i++ && lett++;
break ;
case 'A' ... 'Z':
i++ && lett++;
break ;
default :
i++ && spec++;

cout << "your string has " << i << " characters" << endl ;
//prints the number of numbers in the string
cout << "Your string has " << num << " numbers in it." << endl ;
cout << "Your string has " << lett << " letters in it." << endl ;
cout << "Your string has " << spec << " special characters." << endl ;
return 0 ;

Ben Ben

In your code, int i is not initialized. Using it is Undefined Behaviour.

int i = 0;

The same goes for the rest of your variables. Also this doesnt do what you think it does:

i++ && lett++;

This is not do both operations, its a Boolean operator. It employs something called short circuiting, which means if the first part of the && evalutes to false (ie 0), then the expression must be 0 so there is no point in evaluating the rest of it (ie the lett++ part). So for your first loop (i == 0) your lett++ will be short circuited.

Change these to:


If you fix this up it will work:

Live example