简体   繁体   中英

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.

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM