Thread: Reading in char for float with scanf

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    25

    Reading in char for float with scanf

    I'm using scanf to read floats from input and want to put in error handling to detect when the user is inputting something that isn't a number (that is, a string). When I type in a string, it seems to make a float that is a very tiny number that is close to, but not equal to, 0. The problem is that if I try to account for this by saying floor(inputvariable) can't equal 0, then I can't input a float that's between 0 and 1. What can I do to handle this error?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Check the return value of scanf(); scanf() returns the number of items succesfully read. That is, for scanf("%f"), the return value will be 1 if all was successful or something else (0 or EOF). For scanf("%f%f%f"), the return value could be from 1-3 (or 0 or EOF), indicating how many numbers were read successfully.

    If scanf() detects an error, remove the offending characters from the input stream and resume reading. Something like this:
    Code:
    int c;  /* must be an int to hold EOF */
    double percent;
    
    printf("Enter your percent: ");
    while(scanf("%lf", &percent) != 1) {
        printf("Try again: ");
        while((c = getchar()) != EOF && c != '\n');
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Thanks! Got it now

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    And my after advice is to simply avoid scanf and use fgets with sscanf.
    http://www.daniweb.com/code/printsnippet357.html
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Obtaining source & destination IP,details of ICMP Header & each of field of it ???
    By cromologic in forum Networking/Device Communication
    Replies: 1
    Last Post: 04-29-2006, 02:49 PM
  3. errors in class(urgent )
    By ayesha in forum C++ Programming
    Replies: 1
    Last Post: 11-10-2001, 10:14 PM
  4. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM