Search code examples
cif-statementdev-c++

Incorrect comparison of three input characters


I have the following program, which compares three characters and outputs their comparison.

When I run the program, whenever I input three integers only the last else (all initials are different) statement runs correctly for its condition. But, for other conditions, only the last else if (first and last initials are the same) runs. I also checked it after adding curly braces but nothing changed.

    #include<stdio.h>
    #include<stdlib.h>

    int main()
    {
    char ch1, ch2, ch3;

    printf("Enter 3 character values into ch1, ch2, and ch3: ");
    scanf("%c%c%c", &ch1, &ch2, &ch3);

    if(ch1==ch2)
    {
      if(ch2==ch3)
      printf("All initials are the same!\n");

      else
      printf("First two initials are the same!\n");
     }
 
    else if(ch2==ch3)
    {
    printf("Last two initials are the same!\n");
    }
  
    else if(ch1==ch3)
    {
    printf("First and last initials are the same!\n");
    }
  
  
    else
    {
    printf("All initials are different!\n");
    }
 
   
    system("pause");
    return 0;
    } 

Solution

  • The code you have posted works just fine, so long as you don't enter any whitespace characters between the input initials! (I tested it with AAA, AAB, ABA, ABB and ABC, and all gave the correct response.)

    However, if you were to enter spaces between the initials (i.e. enter A A B), then the space characters will be read as input (that's how the %c format specifier works) so, in that case, the three initials will actually be A, and A – giving a seemingly incorrect answer.

    To skip (optional) whitespace characters between the inputs, simply add a space between each of the %c format specifiers, like this:

    scanf("%c %c %c", &ch1, &ch2, &ch3);