Denim4589
Denim4589

Reputation: 3

how to check char array with nested if statement?

As you might be able to tell im trying to introduce a counter for how many consonants there are in a certain string, but the output is always 50, unless spaces are involved.

int main(){
char input[50];
int total = 0;
cout << "Enter a string of no more than 50 characters\n";
cin.getline(input,50);

for(int n = 0; n<50;n++){
    if(input[n]!='a',input[n]!='A',input[n]!='e',input[n]!='E',input[n]!='i',input[n]!='I',input[n]!='o',input[n]!='O',input[n]!='u',input[n]!='U',input[n]!=' ')
    total++;}

cout << total << endl;}

Upvotes: 0

Views: 591

Answers (2)

thepace
thepace

Reputation: 2221

As everyone has clearly explained, you need to use && operator to ensure all conditions are checked.

    if(input[n]!='a' && input[n]!='A' && input[n]!='e' && input[n]!='E' && input[n]!='i' && input[n]!='I' && input[n]!='o' && input[n]!='O' && input[n]!='u' && input[n]!='U' && input[n]!=' '){
    total++;
}

One recommendation to avoid multiple checks: Extract the character to a variable converted to lower or upper case.

char c = input[n] | 32;

Regarding the ',' used; this program might provide more insight along with the WIKI shared :

void main(){
    int a=-1;
    if(++a,a, a++){ // Works like "||"
       printf("Yes %d",a); 
    }else {
       printf("NO %d", a);
    } 
}

Output: NO 1

Upvotes: 1

niyasc
niyasc

Reputation: 4490

According to wikipedia, comma operator is defined as follows

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In your case, you should use logical AND (&&) instead of comma operation. More efficiently, you may rewrite your code like this

char c = tolower(input[n]);
if (c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c !='u')
    total++;

It will include all the cases.

Upvotes: 3

Related Questions