Gabriel Llamas
Gabriel Llamas

Reputation: 18447

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.

Upvotes: 6

Views: 75657

Answers (4)

wormsparty
wormsparty

Reputation: 2509

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

Upvotes: 4

pmg
pmg

Reputation: 108986

You always executing getchar twice (even when there is no need for that). Try limiting calls to fflushstdin:

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

Upvotes: 0

pabdulin
pabdulin

Reputation: 35255

You should go with:

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

since 13 is ASCII code for Enter key.

Upvotes: 1

Vivek
Vivek

Reputation: 1461

Try

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

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

Upvotes: 2

Related Questions