Results 1 to 5 of 5

Thread: fscanf woes

  1. #1

    Thread Starter
    Hyperactive Member noble's Avatar
    Join Date
    Nov 2000
    Location
    Philly
    Posts
    471

    fscanf woes

    I'm forced to use plain C and i'm having problems with fscanf....

    I'm simply reading in lines from a text file but the last line may
    or may not have a \n and the following piece of code gives
    an exception at the feof test line (i hate using while).

    Any advice on this would be greatly appreciated.

    Code:
    float fData[11];
    
    while(!feof(m_pFile)
    {
         for(int i = 0; i< 12; i++)
              fscanf(m_pFile, "%f", &fData[i]);
    }
    Bababooey
    Tatatoothy
    Mamamonkey

  2. #2
    Addicted Member HairyDave's Avatar
    Join Date
    Aug 2002
    Location
    Er...I can't remember.
    Posts
    196
    You need to test for EOF differently (I think):

    Code:
    while(fscanf(m_pFile, "%f", &fData[i]) != EOF)
    {
      // Do whatever
    }
    If you don't like that you could always use fgets():

    Code:
    while(!feof(m_pFile))
    {
      char szBuff[BUFF_SIZE];  // Depends on how long the lines are
      fgets(szBuff, 10, fPtr);  // Get 10 chars from file - or till end of line
    
      if(ferror(m_pFile))
      {
        // Handle the error
      }
      else
      {
        // Convert the character array to a float
      }
    }
    Or something like that. This allows you to test for errors. Otherwise just use the first example - if it doesn't work, come back and explain the errors.

    HD

  3. #3
    Guru Yonatan's Avatar
    Join Date
    Apr 1999
    Location
    Israel
    Posts
    892
    What's so plain about C?!

    Using a space in the format string will make the scanning function skip several types of whitespace characters:
    Code:
    fscanf(m_pFile, " %f", &fData[i])

  4. #4
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594
    "Plain" C as opposed to C"++"
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  5. #5
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    In that case, it's just "C" or "C++".
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width