Search code examples
cif-statementdo-whilelogical-operatorsgetchar

How to fix - unexpected output using getchar() and do-while


I am trying to make a simple code that will read a char from input and execute "Correct" or "Incorrect input" and run the code again until the correct input is entered. First of all it does not work for capital X. The other issue that I want to fix is that after the incorrect input I have to press enter to get the "Enter x" message, instead of getting in immediately after the incorrect input message.

#include <stdio.h>
int main()
{
         do
         {
            printf("Enter x\n");
            if (getchar()=='x'|| getchar()=='X')
            {
            printf("Entered char is X\n");
            return 0;
            }
            else
            {
            printf("Input incorrect! Please try again!!!\n");
            }
         }
         while (getchar()!='x' || getchar()!='X');
     return 0;
 }

Solution

  • When you hit the ENTER key the newline character \n is placed in input buffer. You need to consume that newline character in order to read the next character.
    Also you are reading two time, which is unnecessary in this case. So your code should be like this

    #include <stdio.h>
    int main()
    {
             char inp;
             do
             {
                printf("Enter x\n");
                inp = getchar();
                getchar(); // reading the newline character '\n'
                if (inp == 'x'|| inp =='X')
                {
                   printf("Entered char is X\n");
                   return 0;
                }
                else
                {
                   printf("Input incorrect! Please try again!!!\n");
                }
             }
             while (inp !='x' || inp !='X');
         return 0;
     }
    

    p.s There is no need to put condition checking in while loop, since you are returning in if condition. while(true) would work fine. Thanks @bruno for pointing that out.