read from file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • askalottaqs
    New Member
    • Jun 2007
    • 75

    read from file

    i have a file that has all those values, each 3 in a line separated by a single space, i want to do some processing over these numbers, whats the most efficient way to read them? (all i could think about is a read function that reads one by one, stores in a char array, until it finds a space, it stops, and translates the char array to a float)

    please help, thnx
  • mattmao
    New Member
    • Aug 2007
    • 121

    #2
    Hi

    once you opened the file with the fopen method, you can use a while loop, inside which contains a fgets method that would store each line of content into a char array.

    Now that you have a char array, you can use strtok method to tokenize the three components out of the array and then use atol method to convert them into their corresponding integer values.

    I guess this answers your question, this is mine approach in my assignment...

    Comment

    • askalottaqs
      New Member
      • Jun 2007
      • 75

      #3
      thanks a lot for your amazingly fast reply! just a small question, im kinda new to c++, and the i dunno how to use the strtok, i checked the documentation, but im gettin lost,

      and btw, what does it mean if it isnt thread safe? what could i do about it? thnx

      Comment

      • oler1s
        Recognized Expert Contributor
        • Aug 2007
        • 671

        #4
        It sounds obvious when I say it now, but you should remember to mention what language you are programming in. fgets/strtok would be useful in C. In C++, you have a better option.

        Actually, it's worth knowing the best logic to use. The best way in both C and C++, usually, is to attempt to read the entire line at once. Then attempt to process that line appropriately.

        Use the getline function in C++ to read in an entire line to a string. Then use stringstreams to store the line in three different doubles. You can repeat the whole reading in process by doing a while(getline(. ..)). getline will effectively return false when you reach the end of the file.

        This topic has been covered before. So I suggest you Google on how to use getline, and then how to use stringstreams. Once you have done so, you will no doubt have more specific questions, and this will make it easier for us to help you out.

        Comment

        Working...