Anand
Anand

Reputation: 13

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.

Upvotes: 1

Views: 2281

Answers (2)

R Sahu
R Sahu

Reputation: 206567

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

   }    
}

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Is this what you want?

#include <stdio.h>
#include <ctype.h>

int
main(void)
{
    char buffer[100];

    while (1)
     {
        char *line;

        printf("Please enter your choice: ");
        line = fgets(buffer, sizeof(buffer), stdin);
        if ((line == NULL) || ((toupper(line[0]) == 'Q') && (line[1] == '\n')))
            break;
        printf("Not done yet!\n");
     }
    return 0;
}

Upvotes: 2

Related Questions