Creating a open file function.

I am trying to create a function which will open a file, read the numbers in a file, place those numbers in an array, and then return those numbers. So far I have:

void getPrices()
{
const int SEAT_PRICES = 2;
double prices[SEAT_PRICES];
int count = 0;
ifstream inputFile;

inputFile.open("C:\\data\\SeatPrices.txt");

while (count < SEAT_PRICES && inputFile >> prices[count])
count++;

inputFile.close();


//This part is just something to display the numbers in the file.
cout << "The numbers are: ";
for (count = 0; count < SEAT_PRICES; count++)
cout << prices[count] << " ";
cout <<endl;
For example you can return container with values. Bonus: it is can hold arbitrary amount of element. Also it is good to make function to take filename as a parameter to allow code reuse:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>


std::vector<double> getPrices(std::string filename)
{
    std::ifstream input(filename);
    std::vector<double> prices;
    std::copy(std::istream_iterator<double>(input), std::istream_iterator<double>(),
              std::back_inserter(prices));
    return prices;
}


int main()
{
    auto prices = getPrices(R"(C:\data\SeatPrices.txt)");
    for(auto v: prices)
        std::cout << v << ' ';
}

Topic archived. No new replies allowed.