Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading enter key in a loop in C

Tags:

c

How can I read the enter key in a loop multiple times?

I've tried the following with no result.

char c;
for (i=0; i<n; i++){
    c = getchar ();
    fflushstdin ();
    if (c == '\n'){
        //do something
    }
}

And fflushstdin:

void fflushstdin (){
    int c;
    while ((c = fgetc (stdin)) != EOF && c != '\n');
}

If I read any other character instead of enter key it works perfect, but with enter key In some iterations I have to press the enter 2 times.

Thanks.

EDIT: I'm executing the program through putty on windows and the program is running on a virtualized linux mint on virtual box.

like image 728
Gabriel Llamas Avatar asked Aug 22 '11 08:08

Gabriel Llamas


2 Answers

Why do you call fflushstdin()? If fgetc() returns something different from \n, that character is completely dropped.

This should work:

char prev = 0;

while(1)
{
    char c = getchar();

    if(c == '\n' && prev == c)
    {
        // double return pressed!
        break;
    }

    prev = c; 
}
like image 99
wormsparty Avatar answered Sep 18 '22 06:09

wormsparty


Try

if (ch == 13) {
  //do something
}

ASCII value of enter is 13, sometimes \n won't work.

like image 41
Vivek Avatar answered Sep 22 '22 06:09

Vivek