Deepak Uniyal
Deepak Uniyal

Reputation: 89

How does scanf() reads when input is not in specified format?

The input and output for the following program are given below:

#include<stdio.h>
int main(){
int a=0, b=100, c=200;
scanf("%d,%d,%d",&a,&b,&c);
printf("%d %d %d\n",a,b,c);
return 0;
}

Input-1:

1,2,3

Output-1:

1 2 3

So the first output is correct and as expected.

Input-2:

1 2 3

Output-2:

1 100 200

Here it reads first integer correctly but I am not able to understand, how the scanf() reads the data after first integer when we are not giving the input in specified format?

As values entered after first integer are not assigned to any variables, What happens to those values?

Are they written on some random memory locations?

Upvotes: 3

Views: 800

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

TL;DR answer: It doesn't. It stops reading.

To clarify, input is not in specified format is a matching failure for scanf(). That is why it's always recommended to check the return value of scanf() to ensure all the input items got scanned successfully.

In the second input scenario, the scanf() has failed to scan all the input parameters because of the format mismatch of expected and received inputs [and you have no idea of that]. Only the value of a has been scanned successfully, and reflected.

[Just for sake of completeness of the answer]:

After the input value of a, due to the absence of a , in the input, mismatch happened and scanf() stopped scanning, returning a value of 1. That's why, b and c prints out their initial values.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182674

Here it reads first integer correctly but I am not able to understand, how the scanf() reads the data after first integer when we are not giving the input in specified format?

scanf stops at the first mismatch and leaves the rest of the target objects untouched. You can inspect the return value to determine how many "items" scanf matched.

As values entered after first integer are not assigned to any variables, What happens to those values?

The unmatched data is left in the input buffer, available for a subsequent read using scanf, fgets etc.


I used getchar() and putchar() after last printf() statement in the program but nothing was read.

Strange. You should be able to get away with something like:

int ch;
while ((ch = getc(stdin)) != EOF)
    putchar(ch);

Upvotes: 6

Related Questions