c

Reading enter key in a loop in 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.


Solution

  • 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; 
    }