-1

I have this loop, but when i hit enter after my character, it processes it and then processes the '\n' before asking for input again. Please!!!! Help

int input;



      while (true){
        input = getchar(); 
        fflush(NULL);
        input = input - '0';
        if( input != 'e' && input != '\n') {
            rc = state_fun(input);
        }

5[ENTER] processes 5 as input, then 10 (which is ascii '\n') as input, then requests input again. It is driving me nuts

i_use_the_internet
  • 604
  • 1
  • 9
  • 28

2 Answers2

0

You can turn off echoing function of the console and only echo back a character if it is not '\n'. If you use linux, you can use this code:

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
int main(){
    struct termios old, new;
    int nread;

    /* Turn echoing off and fail if we can't. */
    if (tcgetattr (STDIN_FILENO, &old) != 0)
      return -1;
    new = old;
    new.c_lflag &= ~(ECHO|ICANON);
    if (tcsetattr (STDIN_FILENO, TCSAFLUSH, &new) != 0)
      return -1;

    char input;
    while (1)
    {
        input = getchar();
        if (input!='\n')
            putchar(input);
    }

    /* Restore terminal. */
    tcsetattr (STDIN_FILENO, TCSAFLUSH, &old);
}

Refer to Hide password input on terminal.

v7d8dpo4
  • 1,399
  • 8
  • 9
0
int input;
while(true) {
    input = getchar();
    getchar(); // <------
    fflush(NULL);
    input = input - '0';
    if( input != 'e' && input != '\n') {
        rc = state_fun(input);
    }
}

Adding an extra getchar() will solve your problem. This is because 5 Enter puts 2 characters on stdin: a '5' and a '\n', which you may not expect.

nalzok
  • 14,965
  • 21
  • 72
  • 139