Thread: Code not working properly.

  1. #16
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    scanf return number of variables it successfully filled with info - it has nothing to do with format types - only number of formats is important

    Code:
    scanf("%d %*s %c", &num, &ch)
    Possible return values are
    EOF - is end-of-file reached on input stream
    0 if num cannot be read using first format (%d in the sample)
    1 if num was read but second parameter was failed to read (%*s is ignored and does not affect the return value at all)
    2 if both variables were filled successfully

    if you have more format specifiers in the string and more variables - return value can be bigger - till the number of vars passed.
    so in most cases the reasonable way to call scanf
    Code:
    if(scanf(format_string, variables) == number_of_variables)
    {
      //handle sucess
    }
    else
    {
     //handle failure
    }
    The only exception I know is %n specifier - that does not counts - so its variable should not be used in the number_of_variables count
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  2. #17
    Registered User
    Join Date
    May 2015
    Posts
    90
    Quote Originally Posted by iiwii View Post
    I misunderstood when "return value" was mentioned, I though it was the value of the variable num1 or num2. After you mentioned that the input "1" and "a" returns a value of 1 I looked online for more information, I found this site https://www.hackerearth.com/notes/printf-scanf-in-c/ does that mean if I use three %d in scanf, there should be a return value of 3?
    If the user inputs three numbers then yes, that's why you need to make a validation.
    What if it was the other way around and I wanted users to input only letters, if I use scanf with %c and a user enters a digit will it return a 0 because I used a %c instead of %d?
    Nope, because it will treat the digit (or the first of them) as a character, the job is on you to make those proper validations.

    Check this out, it will clear some thoughts, it did to me at least.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inequality code doesn't seem to be working properly
    By Sinca in forum C++ Programming
    Replies: 1
    Last Post: 03-12-2013, 11:48 PM
  2. Numbering of code not working properly
    By std10093 in forum General Discussions
    Replies: 14
    Last Post: 09-28-2012, 09:41 AM
  3. Replies: 1
    Last Post: 07-17-2012, 12:56 AM
  4. Reducing rational numbers - code not working properly
    By adrian2009 in forum C Programming
    Replies: 2
    Last Post: 04-17-2009, 07:42 AM
  5. cygwin -> unix , my code not working properly ;(
    By CyC|OpS in forum C Programming
    Replies: 4
    Last Post: 05-18-2002, 04:08 AM