Search code examples
cwhile-loopgetchar

Exit loop when 'Q' is entered


I want to have a program in c where user is asked for input at the beginning of the loop and end the while loop if the user hits Q. I am in search of efficient code and without fflush() call as well.[I consider user can input 'a', 'abc', 'ab2c' etc at the input]. I tried in following manner but if i press 'a' it also includes '\0' which causes additional call for loop. Similarly if user enters 'abc' or 'ab2c' etc. loop is executed multiple times.

int main (void)
{
    char exit_char = '\0';
    puts ("Entering main()");

    while (1)
    {
        printf ("Please enter your choice: ");

        exit_char = getchar();
        if (exit_char == 'Q')
            break;

        f1();
    }
    return 0;
}

please suggest a appropriate solution.


Solution

  • In situations like yours, it's best to read the input line by line, and then process each line.

    #define MAX_LINE_LENGTH 200
    
    char* getInput(char line[], size_t len)
    {
       printf ("Please enter your choice: ");
       return fgets(line, len, stdin);
    }
    
    int main (void)
    {
       char line[MAX_LINE_LENGTH];
    
       while ( getInput(line, sizeof(line)) )
       {
          if ( toupper(line[0]) == 'Q' )
             break;
    
          // Process the line
    
       }    
    }