read text file into formatted struct array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mike91
    New Member
    • Mar 2010
    • 3

    read text file into formatted struct array

    Hello,
    I have a text file of unknown size that I need to read into a struct array where the struct looks like :
    {
    short hours
    float secondsPastHour
    float data1
    float data2
    }

    But the text file is in the format
    hh:mm:ss data1 data2

    I have an array of the struct and I need each line in the text file to be read into one record of the array. I know how to open a file but I am having a hard time finding how to read and reformat the data in the file, and how the colon's are handled in the time string. How can I split this into two separate variables?

    Thanks for the replies!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I assume the data in the file is in text format. Like 12:15:20.

    All you need to is read into an int, a char, an int, a char and an int. Then move these variables you your struct variables.

    BTW: Your struct variables should be int and not float.

    Comment

    • mike91
      New Member
      • Mar 2010
      • 3

      #3
      The data for the time is in hh:mm:ss.ss format, yes, for example, 12:15:20.57 would be 12:15 and 20.57 seconds. The secondsPastHour needs to be a float. Also, the two data fields are both floats.

      How can I read in an int and have it stop at the colon? Can you just give me a quick code snippet of this? I can't figure out which read routine is best for it.

      Thanks.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        In C++ if you have 10:20:30 all you do is:

        Code:
        int hr;
        int min;
        int sec;
        char colon;
        
        infile >> hr >> colon >> min >> colon >> sec;
        In C you just use scanf().

        BTW: 20.57 is not a float. It is 2057. Use an int in your struct. It would represent two thousand fifty seven hundredths of a second. You can always display it as 20.57. This works just like money where you keep your data in pennies. 2057 pennies is $20.57.


        Code:
        infile >> sec >>thedot >> hsec;
        
        sec *= 100*sec;   //convert ss to hundredths of sec
        sec += hec;         //sec should now have 2057.

        Comment

        • mike91
          New Member
          • Mar 2010
          • 3

          #5
          After the file read, I'm using fscanf(filename , "%i,%c,%i,%c,%i ",&hours,&colon ,&minutes,&colo n,&seconds);

          with just the time on a line in the text file and the only thing being read in is the hours, the minutes and seconds end up as zero.

          --- nevermind this post-- I figurred it out, Thakns for the help.

          Comment

          Working...