Home > Mobile >  User Input of Integers Infinite Loop Until User Inputs a Character (C language)
User Input of Integers Infinite Loop Until User Inputs a Character (C language)

Time:12-06

User Input of Integers Infinite Loop Until User Inputs a Character (C)

int n = scanf("%d", &i);  
if (n == 1) {

can somebody explain me this part I am unable to understand why equality operator does not give false as output and jumps to else statement??

i am a beginner and don't much about these complicated syntax. Pls help me

   int n = scanf("%d", &i);  
    if (n == 1) {

if i give 5 as input then value of n will be 5 and when it goes to if statement then (5==1) will execute which will results as false but in this answer it not that case ?

CodePudding user response:

No, that certainly is not the case. As per the man page:

RETURN VALUE

On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

So in the case of a single integer, if scanf was successful in reading and assigning it to a memory address as specified in the second argument, it will returns the number of elements successfully processed.

Aside:

You do not need to declare another variable and assign the return value of scanf to it, you could test for it directly:

if (scanf("%d", &i) != 1) { 
    ..deal with invalid input..
}
  • Related