Ashish
Ashish

Reputation: 33

how scanf works if character is given as input in place of integer

do
{
    printf("minutes: ");
    scanf("%d", &minutes);
}while(minutes < 1);

For above code if minutes is given some character then minutes has the value "2". If some negative integer given as input first then a character, the statement "minutes: " repeats for infinite times.

I ran this program in codeblocks. Why it is happening?

Upvotes: 2

Views: 57

Answers (2)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

scanf("%d",&minutes) will not read the value of the character. The value in minutes will be unchanged. The character will remain in the buffer and scanf will keep trying to read it and keep failing.

The return value of scanf will be the number of elements read, so it will be 0 if you feed in a character, and that can be used to break the loop.

do
{
  printf("minutes: ");
  ret = scanf("%d", &minutes);
  if (ret != 1)
     break;
}while(minutes < 1);

Upvotes: 4

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

It returns 0 in this case. The scanf() function returns the number of matched format specifiers. In this case, none matched and hence it returns 0.

If you initialize number before calling scanf() and it then fails returning 0, the value you used to initialize number doesn't change after the call to scanf().

If you don't initialize number, then trying to read the value is undefined behavior. It will have an undeterminate value so you can't predict which value it will be.

Upvotes: 0

Related Questions