Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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 ?

>Solution :

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..
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading