I have a Runner
class which has three member variables (firstName
, lastName
, and pace
), and a default constructor that does nothing.
I'm trying to read from a file that stores firstName
, lastName
, and pace
, then assign the values to a Runner
object before adding it to a vector.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "runner.h"
using namespace std;
int main(){
ifstream input("test.txt");
vector<Runner> list;
string holdFN;
string holdLN;
int holdP;
int x=0;
while (x!=1){ //Shows whether opening was successful
if (input.is_open()){
cout << "\nFile Opened Successfully.\n\n";
x++;
} else {
cout << "\nFile Failed to Open.\n\n";
}
}
while (input.eof()!=1){
Runner runner;
input >> holdFN >> holdLN >> holdP;
runner.firstName = holdFN;
runner.lastName = holdLN;
runner.pace = holdP;
list.push_back(runner);
}
for (int i=0; i<list.size(); i++){ //Testing to see if vectors stored correctly
cout << list[i].pace << " ";
}
return 0;
}
When I don't involve a while
loop and just have the loop's "guts", the code works and I get a successful output of the object's pace
from the vector
.
However, when I run the code as it currently is above, I get the following output:
File Opened Successfully.
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I'm not sure how to fix this. Does anyone have any ideas?