-1

First question! Very new to programming. I am looking to print an asterisk whenever a player has entered either 'a' or 'b' after a get_string function. Running this code and entering either 'a' and 'b' does not produce an asterisk whereas entering 'c' does produce an asterisk.

  1. Why does it produce an asterisk only for the 'c' input?

  2. What is the correct way to use of the OR function here?

Thanks for your help!

for(int i=0;i<strlen(input);i++)
    {
        if (input[i] == ('a' | 'b'))
                {
                    printf("*");
                }
    }
DrRelish
  • 3
  • 1

3 Answers3

3

What is the correct way to use of the OR function here?

Like this:

if (input[i] == 'a' || input[i] == 'b')

Why does it produce an asterisk only for the 'c' input?

I suggest reading about what the | operator does. It is the bitwise or operator, which is different from || which is the logical or operator. You can read about it in another answer I wrote. Also, character literals like 'a' are just plain integers in disguise.

klutt
  • 30,332
  • 17
  • 55
  • 95
3

If you have more characters to look for then a chain of || is getting cumbersome. Alternatively you can use strchr.

if (strchr("ab", input[i]))
tstanisl
  • 13,520
  • 2
  • 25
  • 40
2

The correct syntax is

for(int i=0;i<strlen(input);i++)
{
    if (input[i] == 'a' || input[i] == 'b')
    {
        printf("*");
    }
}

What you're currently doing is bitwise-ORing 'a' and 'b' (which evaluates to 99 (the ASCII character c)), and comparing the value to that.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • There's something about nested parenthesis that just does not look right in plain text :D – klutt Oct 15 '21 at 10:59