Using getchar () on c gets 'Enter' after input

I am trying to write a simple program that asks the user to select from a menu in a loop. I use getchar () to get input, however I noticed that when I type char and press "Enter", the program does two loops (as if I pressed twice), one char as input and the other for "Enter". as an input.

How to fix it?

+7
source share
6 answers

You need to read about canonical and noncanonical entry. The following stack overflow issue solves the following:

canonical-vs-non-canonical-terminal-input

+3
source

Add getchar()after getchar(): P

+2

- getchar

char c = (char)getchar();
if ( c != '\n' ) {
  ...
}
+2

getchar() . (\n ). getchar() :

void clearInputBuffer() // works only if the input buffer is not empty
{
    do 
    {
        c = getchar();
    } while (c != '\n' && c != EOF);
}
+2

#include <stdio.h>

/*! getline() reads one line from standard input and copies it to line array
 * (but no more than max chars).
 * It does not place the terminating \n in line array.
 * Returns line length, or 0 for empty line, or EOF for end-of-file.
 */
int getline(char line[], int max)
{
  int nch = 0;
  int c;
  max = max - 1;            /* leave room for '\0' */

  while ((c = getchar()) != EOF) {
    if (c == '\n')
      break;

    if (nch < max) {
      line[nch] = c;
      nch = nch + 1;
    }
  }

  if (c == EOF && nch == 0)
    return EOF;

  line[nch] = '\0';
  return nch;
}

+1

- ; .

. , scanf() :

printf("Pick an option: ");
fflush(stdout);
scanf("%d", &option);
switch(option)
{
  case 0 : do_something(); break;
  case 1 : do_something_else(); break;
  ...
  default: bad_option(); break;
}

, %d , , , \n ( , , %c , , getchar()).

, - , %d getchar() scanf() %s %c.

The best option is to read all the input as character strings using fgets(), then analyze and validate as needed.

/**
 * Prints a prompt to stdout and reads an input response, writing
 * the input value to option.  
 *
 * @param prompt [in]  - prompt written to stdout
 * @param option [out] - option entered by user
 *
 * @return - 1 on success, 0 on failure.  If return value is 0, then option
 * is not changed.
 */
int getOption(const char *prompt, char *option)
{
  char input[3]; // option char + newline + 0 terminator
  int result = 0;

  printf("%s: ", prompt);  
  fflush(stdout);

  if (fgets(input, sizeof input, stdin))
  {
    /**
     * Search for a newline character in the input buffer; if it not
     * present, then the user entered more characters than the input buffer 
     * can store.  Reject the input, and continue to read from stdin until
     * we see a newline character; that way we don't leave junk in the
     * input stream to mess up a future read.
     */
    char *newline = strchr(input, '\n');
    if (!newline)
    {
      printf("Input string is too long and will be rejected\n");
      /**
       * Continue reading from stdin until we find the newline
       * character
       */
      while (!newline && fgets(input, sizeof input, stdin))
        newline = strchr(input, '\n');
    }
    else
    {
      *option = input[0];
      result = 1;
    }
  }
  else
    printf("Received error or EOF on read\n");

  return result;
}

Yes, it is a lot of work to read in one silly menu, and that is a simple version. Welcome to the wonderful world of interactive input processing in C.

+1
source

All Articles