Since your textfile is whitespace delimited, you can use that to your advantage by utilizing std::istream
objects who skip whitespace by default (in this case, std::fstream
):
#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
int main() {
std::ifstream ifile("example.txt", std::ios::in);
std::vector<double> scores;
//check to see that the file was opened correctly:
if (!ifile.is_open()) {
std::cerr << "There was a problem opening the input file!\n";
exit(1);//exit or do additional error checking
}
double num = 0.0;
//keep storing values from the text file so long as data exists:
while (ifile >> num) {
scores.push_back(num);
}
//verify that the scores were stored correctly:
for (int i = 0; i < scores.size(); ++i) {
std::cout << scores[i] << std::endl;
}
return 0;
}
Note:
It is highly recommended to use vectors
in lieu of dynamic arrays where possible for a myriad number of reasons as discussed here:
When to use vectors and when to use arrays in C++?