Kalanidhi
Kalanidhi

Reputation: 5092

How Terminate scanf() without entring the value?

#include "stdio.h"
main()
{
    int option;
    printf("Enter the value :");
    scanf("%d",&option);
    printf("Your value is %d\n",option);
}

This is my simple C program to get the value form the user and print it. I have a doubt why scanf waits till the values is entered, it does not terminate when \n ie., enter key is pressed.

For example :

16:26:40-$./a.out
  Enter the value: <-|
<-|
<-|
<-|
<-|
<-|
<-|
   1
Your value is 1

I need clear concept and what is the solution for this?

Thanks in Advance

Upvotes: 1

Views: 7537

Answers (4)

RATriches
RATriches

Reputation: 11

How Ted has mentioned, 'fclose(stdin);' worked well for me too.

At "main" I added:

if (signal(SIGINT, handler_SIGINT) == SIG_ERR) {
  printf("Fail capture SIGINT\n");
}

sig handler :

static void handler_SIGINT(int sig) {
  printf("CTRL+C\n");
  fclose(stdin);
}

Upvotes: 1

Ted
Ted

Reputation: 1

What if you put an fclose(stdin) in the SIGINT handler? Worked for me, but probably not the best practice:

void quitproc(int in)
{
    printf("Got the Ctrl-C\n");
    ExitLoop = 1;

    // This will exit scanf
    fclose(stdin);
}

Upvotes: 0

haccks
haccks

Reputation: 106012

How scanf works:

For each conversion specifier in the format string of scanf, it tries to locate an item of the appropriate type in the input, skipping blank space if necessary. It then reads the item and stops when encounters a character that doesn't belongs to the data item.

In case of

scanf("%d",&option);  

option is int data type. scanf searches for the beginning of a number and ignores white-space characters (newline, space, tab etc.) and that's why it waits till an integer is entered.

Upvotes: 2

flyman
flyman

Reputation: 210

you are right.. scanf is not always good. i would do something like this:

#include "stdio.h"

void main( void )
{
    int option;
    int res;
    char buff[20];
    printf("Enter the value :");
    gets(buff);
    res = sscanf(buff,"%d",&option);
    if(res == 1)
        printf("Your value is %d\n",option);
}

gets terminates at newline and stores the string in buff. sscanf reads like scanf (same format) but from c-string input instead of stdin.

sscanf (and also scanf) returns the number of items in the argument list successfully filled or EOF if it fails to read anything. since we fill only 1 item, we check: if(res == 1).

maybe there some better ways to do this, but i think this is similar to your code, so it may be easier for you to change the code when needed.

Upvotes: 1

Related Questions