I'm trying to make my program read in data from a data (.dat) file (which is really just a text file). So of course I'm using the loop condition while(!file.eof())
, but this is never returning true. Here's my function:
void Table::readIn(const char finput[]){
std::ifstream file;
file.open(finput);
if (!file.is_open())
{
std::cout << "Cannot open " << finput << std::endl;
return;
}
char key[100];
file.get(key, 99, '\n');
while (!file.eof())
{
stock * item = new stock;
item->setTick(key);
file.get(key, 99, '\n');
item->setName(key);
file.get(key, 99, '\n');
item->setValue(atof(key));
file.get(key, 99, '\n');
item->setDate(key);
file.get(key, 99, '\n');
item->setYearReturn(atof(key));
file.get(key, 99, '\n');
addStock(item);
}
}
and here's what's in my data file:
TSLA
Tesla Motors, Inc.
30160000000
November 6, 2015
13.1
I wish I could give you guys more information, but the fact that the program is looping through the while (!file.eof())
loop indefinitely is all I know about this issue.
Edit: I ran this through a debugger, with a break point at every line of the while
loop. What I found is that the first get()
call (before the while
loop) sets key
to the correct value, but every get()
call after that sets key
to ""
. I'm assuming this is because the program is never reading past first '\n'
character in the file. Do you guys know how to fix this?
Edit 2: This question is different from: Why is iostream::eof inside a loop condition considered wrong? because I have to read in more than one line each time I run through my while
loop.