Home > Software engineering >  scanf stops taking inputs from the commandline once you feed into it (the command line) an input tha
scanf stops taking inputs from the commandline once you feed into it (the command line) an input tha

Time:01-24

Here's my code. When it asked for my first input on the command line, I entered '5cde'. Then it printed '5', and it didn't ask for any more inputs before termination.

How is this okay? Is there a way to see how scanf is working internally as I run this program? I really want to know what exactly is going on behind the scenes. I'm not sure how the input buffer works, and if I should even be messing with it. Or should I just use a different io function instead? Because scanf seems pretty unsafe to me.

int i;

scanf("%d", &i);
printf("%d", i);
scanf("%d", &i);
scanf("%d", &i);
scanf("%d", &i);
scanf("%d", &i);

CodePudding user response:

when you write %d it expects a number. You get wrong answer because of entring charachters.

CodePudding user response:

You should check the result of each scanf call. It returns the number of items successfully read (or EOF in case of failure) so in your case it should return 1 or otherwise something went wrong.

Please also note that each time you hit enter during input, there's a trailing line feed character added to stdin which needs to be discarded, if you were for example to read a string after reading a number. This should be addressed early on in your C book, if it's any good.

Overall scanf is to be regarded as a quick & dirty function for simplistic programs and not something to be used in real production code, so you don't really need to worry about leaning all the details of it. Using fgets and reading everything as strings is much better (and faster) practice.

CodePudding user response:

The behavior of the function scanf when the conversion specifier d is used is the following

d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer

So for this input buffer

5cde

the first call of scanf reads the character 5 because it represents a valid integer number and the position in the input buffer moves to the right at the character 'c'.

When the next and subsequent calls of scanf failed because the symbol 'c' is not a valid digit. The position in the input stream stays the same.

You should check whether call of scanf was successful> For example

if ( scanf("%d", &i) == 1 )
{
    printf("%d\n", i);
}
else
{
    // remove the invalid input
    scanf( "%*[^\n]%*c" );
} 
  •  Tags:  
  • Related