Thread: Using fscanf for reading numerical data from text file

  1. #1

    Question Using fscanf for reading numerical data from text file

    Please, could someone give me a hint?

    I have to read numerical data from a text file. The numbers to be read from file have at most 8 algarisms. I tried to read the data using fscanf, but it doesn't work properly. Here an example of the numerical data which can be found in the file:

    1234567812345678 1234567 123456 12345

    That means, when the numbers have 8 algarisms, there are no spaces between then, but if they have less algarisms, there are some spaces.

    If I write : fscanf(%8d,....etc), only the first two numbers are read correctly (12345678) but it fails for the following entries. The third entry is read as 12345671, the fourth as 23456123 and the fifth as 45

    What should I do do read the numbers correctly, when spaces exist?

    Or can't I use fscanf in this case?

    It is possible to use another function, for example fread? Or fread works only with binary files?

    Thanks for any help!!!


  2. #2
    Registered User sean345's Avatar
    Join Date
    Mar 2002
    fscanf should work. I am not to experienced in using it though. I would try using fgets. You could capture the whole line using fgets and then parse the line and take the numbers. For example strncpy() the first 8 to another string, add a null terminator and then using atoi() to turn the string into an int.

    - Sean
    If cities were built like software is built, the first woodpecker to come along would level civilization.
    Black Frog Studios

  3. #3
    going along with sean, read it in using fgets(), then break up the numbers using strtok(), then use atoi() to turn them into numbers

    strtok is the only one of those you may have a challenge with, just use the MSDN and mess with it till it works

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 01:59 PM
  4. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM
  5. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 10:47 AM
Website Security Test