0

i'm making a simple program but there is a problem, boolean always evaluate as true, i don't know what happen, did i missing something or what? please help

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main ()
{
char kar;
cout<<"Masukan Karakter = ";
cin>>kar;

bool vokal = (kar == ('A','I','U','E','O','a','i','u','e','o'));

string keterangan = vokal ? "Huruf Vokal" : "Bukan Vokal";

cout<<keterangan;

return(0);
}
arghol
  • 745
  • 9
  • 21

1 Answers1

3

This:

('A','I','U','E','O','a','i','u','e','o')

does not represent a set or whatever you think it does. Everything between those ',' (commas) is considered to be an expression. That part of the code evaluates every expression from left to right, and returns the rightmost evaluation.

In your case: expression 'A' evaluates to 'A', 'I' evaluates to 'I', ..., 'e' evaluates to 'e' and 'o' evaluates to 'o'. After every expression is evaluated, value 'o' is returned. That's why your kar will always be compared with 'o' and this code would behave the same as yours:

bool vokal = (kar == 'o');

What you actually need to do is compare kar with every one of those characters, seperately (using the OR ('||') operator in your case):

bool vokal = (kar == 'A' || kar == 'I' || kar == 'U' || kar == 'E' || kar == 'O' 
           || kar == 'a' || kar == 'i' || kar == 'u' || kar == 'e' || kar =='o');
PajLe
  • 791
  • 1
  • 7
  • 21