1

I've written the following to read doubles from an input file, but it seems cumbersome, what other method(s) could I use? Are there pros/cons that I should be aware of?

I would think that this method would be the most accurate since there shouldn't be any binary<->decimal conversion issues, is that correct?

#include<string>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>

void Stats::fill()
{
    string temp;
    stringstream convert;

    statFile.open("statsinput.txt");
    for(int i = 0; i<maxEntries && !statFile.eof(); i++)
    {
        getline(statFile, temp);
        convert<<temp;
        convert>>stats[i];
    }
    statFile.close();
}
Daniel B.
  • 1,254
  • 1
  • 16
  • 35
  • Never use `.eof()` as a loop condition. It almost always produces buggy code, as it has in this example. [See here](http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line) for more info. – Robᵩ Jan 23 '13 at 06:38
  • I didn't realize this was buggy code, but I'll take your word for it, and thank you for the link. – Daniel B. Jan 23 '13 at 06:43
  • Oh I see. The way I have it written, it would try to record the final value twice because the eof wouldn't actually be reached yet. – Daniel B. Jan 23 '13 at 18:35
  • Yep. `getline` would then fail and `temp` would have nothing useful. – Robᵩ Jan 23 '13 at 18:37

2 Answers2

3

Use the input operator directly in the file?

for(int i = 0; i<maxEntries && statFile >> stats[i]; i++)
    ;

Remember that all input streams inherit from the same base classes, so all operations you can do on streams like stringstream or on cin you can on all other input streams as well.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • um ... OK, I think. So the input operator will break at the first whitespace it hits, rather than a /n or EOF? – Daniel B. Jan 23 '13 at 06:38
  • @DanielBall Newline is a whitespace character, as well as space and tab. The input operator for numbers (integer and floating point) skips leading whitespace, read the number, and stop on next whitespace. And of course reading will stop on EOF as well. – Some programmer dude Jan 23 '13 at 06:40
  • Well, it looks like that was a simple question with a simple answer! Thanks very much for helping a newbie :D So does the input operator function differently for other data types? – Daniel B. Jan 23 '13 at 06:42
1

If you have modern C++ (C++ 11) compiler, you can use std::stof, std::stod or std::stold functions.

You could then write:

 getline(statFile, temp);
 double d = std::stod(temp);

More info on C++ Reference page

Wacek
  • 4,326
  • 2
  • 19
  • 28