Thread: fscanf() floating point error

  1. #1
    Registered User
    Join Date
    Feb 2009

    fscanf() floating point error

    Does scanf() have a known problem with floating points when used as below?
    while( (scoresScanned = scanf("%f%f%f", &score1, &score2, &score3)) != EOF  ){
    			if( scoresScanned == 3 ){
    If it do 4.4 5.5 abc it fails like I want it to.
    If I do 4.4 5.5 4abc5 it thinks I entered 4.0 as the last value.

    My understanding of scanf() is that it should fail and return 2 in the latter case.

    Why does scanf() do that? I hoped it would fail instead of truncate the input and append a .0. Perhaps there is a great document of this but I haven't found one.

    I'm studying C in school which would explain why I'm asking about a deprecated function in the first place.


    MS VC++ 2005 Express
    C++ Language Extentions Off \Za
    Compiling as C code \Tc
    Last edited by folderol; 02-19-2009 at 06:47 PM.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    No, scanf makes a best attempt of reading as much as possible of whatever is fed into it until it finds something that is wrong. So if you have a %f format, and give it 4abc, it will read 4 and say "Yes, I got something". It doesn't know that you are NOT expecting to see a %s in the next scanf statement.

    is undefined. fflush, in the standard, is only defined for OUTPUT streams, not input streams. It MAY do what you want, but it's also perfectly within the C library producers right to format your hard-disk, spew out garbage, thrash some random bit of memory, do nothing, crash the application or something else. That's the unfortunate thing about "undefined behaviour" - it is not defined, and may do many different things, depending on circumstances.

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Crazy errors caused by class, never seen before..
    By Shamino in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 11:54 AM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. pointer to array of objects of struct
    By undisputed007 in forum C++ Programming
    Replies: 12
    Last Post: 03-02-2004, 03:49 AM
  5. Couple C questions :)
    By Divx in forum C Programming
    Replies: 5
    Last Post: 01-28-2003, 12:10 AM
Website Security Test