-
reading from a file
Hey yuo guys here's my code which doesn't have any errors or warnings but still doesn't open a file to read data
Code:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;
const int SIZE = 12;
class CStudentInfo
{
public:
string name;
int test1, test2, test3, test4;
};
void readData(CStudentInfo [], int &);
void printData(CStudentInfo [], int &);
int main()
{
int num;
CStudentInfo studentGrades[SIZE];
cout << "Hello, reading the data..." << endl << endl;
readData(studentGrades, num);
printData(studentGrades, num);
cout << "Done" << endl;
return 0;
}
void readData(CStudentInfo studentGrades[], int &num)
{
int count;
ifstream infile;
infile.open("data.txt");
if(!infile.is_open())
{
cout << endl << "ERROR: Unable to open file infile!" << endl << endl;
system("PAUSE");
exit(1);
}
count = 0;
while(!infile.eof())
{
infile >> studentGrades[count].name;
infile >> studentGrades[count].test1;
infile >> studentGrades[count].test2;
infile >> studentGrades[count].test3;
infile >> studentGrades[count].test4;
count++;
}
num = count;
infile.close();
return;
}
void printData(CStudentInfo studentGrades[], int &num)
{
ofstream outfile;
outfile.open("output.txt");
if (!outfile.is_open())
{
cout << endl << "ERROR: Unable to open file!" << endl << endl;
system("PAUSE");
exit(1);
}
outfile << "Name " << "Test1 " << "Test2 "
<< "Test3 " << "Test4" << endl << endl;
int count;
for(count = 0; count < num; count++)
{
outfile.width(17);
outfile << left << studentGrades[count].name;
outfile.width(5);
outfile << left << studentGrades[count].test1;
outfile.width(5);
outfile << left << studentGrades[count].test2;
outfile.width(5);
outfile << left << studentGrades[count].test3;
outfile.width(5);
outfile << left << studentGrades[count].test4 << "\n";
}
outfile.close();
return;
}
-
Is the data file in the correct location? If you are running the program from your IDE the data file usually must be in the same directory as your project files. If you are running your program outside the IDE then the data file must be in the current working directory. Normally when I have problems opening a data file for reading I will try to open a uniquely named file and then see if my data file is in the same directory as this uniquely named file. If I can't create the file for writing then I check to insure that I have write access to the directory in question. The reason I use a unique name for the output file is to make locating this file easier.
Jim