Reputation: 93
Simple program to open up a file and read it's contents. Then a test at the end to see if I did in fact get the information. Every time I run it it tells me that it cannot open the file. I will post the contents of SaleSlips below. Why isn't it opening the file? It is also attempting to delete the file every run as well.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct SaleSlip{
char name[20];
int prodID;
double value;
};
void main(){
fstream slips;
SaleSlip sales[17];
slips.open("SaleSlips.txt", ios::in);
if(slips.eof()){
cout << "Cannot open file - SaleSlips.txt"<< endl;
system("pause");
exit(2);
}
int i = 0;
while(!slips.eof()){
slips.getline(sales[i].name, ' ');
slips >> sales[i].prodID;
slips.ignore(5, ' ');
slips >> sales[i].value;
slips.ignore(80, ' ');
i++;
}
cout << sales[1].value;
slips.close();
system("pause");
}
Eric 1 200000.00
Sookie 2 200.00
Sookie 4 200.50
Upvotes: 0
Views: 3112
Reputation: 125749
You have two problems:
You're opening the file for output (writing)
slips.open("SaleSlips.txt", ios::out);
Useios::in
instead for input (reading)
slips.open("SaleSlips.txt", ios::in);
Next, you're immediately testing for !eof()
, which is the wrong logic.
if(!slips.eof())
You don't want to be at eof()
when opening the file for input. eof()
is end of file
. When first opening the file for input you want to be at the beginning of the file; being at eof()
is a bad thing. Your code should error out if eof()
is true, not if it's false:
if(slips.eof()) {
// It's an error if we're starting at eof()
}
Upvotes: 0
Reputation: 2066
You're opening the stream in output mode by using ios::out
. Use ios::in
to read from it.
You've got a lot of other issues, too. IE:
-The if(!slips.eof())
after the file open will always cause an exit unless the file is empty.
-In your while loop, you are (probably accidentally) attempting to write the prodID and value into the slips file using <<
. Use >>
to read from a stream and <<
to write to it.
Upvotes: 3