1

Scanf should return the number of characters taken as inputted..but strangely returning only 1 all the time.

scanf ("%d",&num_test_cases);   

for (i=0;i<num_test_cases;i++)
{
    level=scanf ("%s",ch);
    printf ("\n %s\n",ch);
    printf ("%lld\n",level);

}

Sample Input :

4
lrl
rll
r
lllr

Output :

lrl
1
rll
1
r
1
lllr
1
3
  • I am guessing you are expecting scanf to return the number of characters entered and that is not how scanf works. You asked scanf to scan one item (%s) and it returned that it succesfully scanned in one item. Commented Sep 5, 2014 at 14:21
  • Returning 1 is good. It means something was stored in ch. 0 means nothing was read (unlikely here). EOF means stdin isat end-of-file (closed). Commented Sep 5, 2014 at 14:40
  • C11dr §7.21.6.2 16 "The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure." Commented Sep 5, 2014 at 14:42

1 Answer 1

8

In C, scanf() returns number of items successfully read... Actually,printf() returns the number of characters successfully written on the output!

So,as your scanf is accepting only 1 input for each iteration,hence,level variable in your program is returning 1 as a result in each iteration!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.