How to read data like this "9.27848E-01" from a file into a C program?

This is a discussion on How to read data like this "9.27848E-01" from a file into a C program? within the C Programming forums, part of the General Programming Boards category; Is there an easy way to read data, expressed in engineering units, into a C program from a text file? ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    4

    How to read data like this "9.27848E-01" from a file into a C program?

    Is there an easy way to read data, expressed in engineering units, into a C program from a text file?

    I have a file containing data that has a single column of numbers like this:

    9.27848E-01
    -3.89783E-01

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    This is scientific notation. I would suggest you to
    • open file with fopen (don't forget to check that the file pointer is not NULL)
    • read data with fread into a char buffer (do that in a loop until you find EOF)
    • every cell has a line of the data that are in file
    • close the file with fclose


    Welcome to the forum!
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    You can do this with scanf. Example

    Code:
    double num;
    while ((scanf("%lf", &num) == 1)) 
         printf("Got num: %.8f\n", num);

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    With fcanf you mean I suppose.

    Better choice
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,676
    Open the file in text mode, then use fscanf with the "%f" modifier for storing the value in a float, or "%lf" for storing in a double.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. "Data Fork"/"Alternate Data Streams"
    By phantomotap in forum Tech Board
    Replies: 3
    Last Post: 08-06-2010, 12:01 PM
  2. Replies: 9
    Last Post: 06-17-2008, 12:38 PM
  3. Replies: 21
    Last Post: 06-16-2008, 03:44 PM
  4. Replies: 9
    Last Post: 05-29-2008, 03:08 PM
  5. Data types to read and hold a "dictionary"
    By maxorator in forum C++ Programming
    Replies: 2
    Last Post: 11-04-2006, 02:09 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21