Search code examples
c++arraysvectorifstream

Import Set of Doubles to an Array From File C++


What I'm attempting to accomplish, is to open an external .dat file using "ifstream" then read each double into a vector array.

What I have:

//Setup I/O
ifstream fileIn;
ofstream fileOut;

//Define vector for file data
vector<double> fileData;

fileIn.open("/FilePath.../checkIn.dat");
//If opening failed, display this text.
if (fileIn.fail( ))
{
    cout << "    Input file opening failed.\n";
    //stop program
    exit(1);
}

The file I'm reading from:

2000 1 1225.72 1 463.81 3 200 1 632 2 1500 1 300 2 1800

I've been looking all around the internet, can't find something useful. I'm looking for a function similar to "hasNextDouble" in Java.


Solution

  • It sounds to me like you're trying to imitate Java too closely (i.e., make things much more complex than necessary).

    // Open the file
    std::ifstream file_in("/FilePath.../checkIn.dat");
    
    // Create the vector, initialized from the numbers in the file:
    std::vector<double> fileData((std::istream_iterator<double>(file_in)),
                                  std::istream_iterator<double>());
    

    ...and you're done.