Distat Kanthasaksiri
Distat Kanthasaksiri

Reputation: 13

How to prevent scanf() from terminating when user presses enter key?

If enter key is pressed, scanf() stops taking inputs hereafter. I've tried many ways: changing data to string and comparing it to null, comparing to ASCII. But, I could not prevent scanf from terminating when user presses enter.

Upvotes: 1

Views: 2888

Answers (3)

Michi
Michi

Reputation: 5297

There are a lot of possible ways to catch this.

See this, for instance:

#include<stdio.h>

int main(void){
    char enterCheck;
    int check;

    do{
        printf("Hit Enter:> ");
        if((scanf("%c",&enterCheck)) == 1){

            if (enterCheck == 10){
                printf("You pressed ENTER\n");
            }else{
                printf("You didn't press ENTER\n\n");
                while((check = getchar()) != 0 && check != '\n');
            }
        }else{
            printf("There was an Error!\n");
        }
    }while(enterCheck != 10);
    return 0;
}

Output:

michi@michi-laptop ~ $ ./program 
Hit Enter:> dsadas
You didn't press ENTER

Hit Enter:> 12
You didn't press ENTER

Hit Enter:> 
You pressed ENTER

So as you can see, the program asks for ENTER key. If you don't hit it, it will ask again, and again.

Now take a closer look, think and try to change this program to do what you need. Think how you would do it when you need to check if user pressed Enter.

Upvotes: 0

Aganju
Aganju

Reputation: 6395

I think you did not fully understand how scanf works.

if you ask scanf to read an integer (by using %d), it will read an integer. As long as there is no reason to stop waiting for an integer, it will not stop - why would it. The part you probably missed is that sscanf is ignoring 'whitespace' - all RET, TAB, SPACE, etc., are ignored, everything that would not produce visible output on a screen.

That means if you hit RET, TAB, SPACE, they will be ignored, and scanf will still wait for your integer.

If you use another key, like any character, it is clear that this is not going to be an integer, and it will stop reading and return to the program (with a status of 0 = zero successful assignments).

Upvotes: 2

R Sahu
R Sahu

Reputation: 206577

  1. Read a line of text using fgets.
  2. If fgets is able read the line without error, use sscanf to read the number from the line.
  3. If sscanf is successful, use the number. Otherwise, go to error handling code.

char line[LINE_SIZE];
if ( fgets(line, LINE_SIZE, stdin) != NULL )
{
   int number;
   if ( sscanf(line, "%d", &number) == 1 )
   {
      // Use the number
   }
   else
   {
      // Deal with error
   }
}

Upvotes: 6

Related Questions