Search code examples
c++fstream

What are other ways to read double from an ifstream besides using getline() and converting with stringstream?


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();
}

Solution

  • 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.