当程序在从文件读取后尝试打印出文件内容时,我一直收到此错误。我的程序能够从文件中读取,但无法将文件中的内容打印到屏幕上。我还想将数据作为指针传递,以便稍后在程序中对数据进行排序,但我的printFile函数给我带来了问题。我的文本文件位于.cpp程序所在的位置。我不确定错误在哪里。
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
const int MAX_SIZE = 50;
struct stdRec
{
string fname, lname, email, id;
double gpa;
};
void mainMenu();
void readFile(int & count, stdRec Stud[], stdRec *pStud[]);
void printFile(int count, stdRec *pStud[]);
//void sort(stdRec *pStud[], int & count, int & choice); //ignore
int main()
{
int choice = 0;
int count = 1;
stdRec Students[MAX_SIZE];
stdRec *pStudents[MAX_SIZE];
readFile(count, Students, pStudents);
do
{
mainMenu();
cin >> choice;
switch (choice)
{
case 1:
{
printFile(count, pStudents);
break;
}
case 7:
{
cout << "\nBye!\n";
break;
}
/*case 2:
case 3:
case 4:
case 5:
case 6:
{
sort(pStudents, count, choice);
break;
}*/
default:
{
cout << "Invalid entry, try again.";
}
}
} while (choice != 7);
system("pause");
return 0;
}
void mainMenu()
{
cout << "\n\t\tMain Menu\n\n" << "1. Print records.\n" //opens and prints unsorted from the file
<< "2. Sort by id.\n" //sorts by id
<< "3. Sort by first name.\n" //sorts by first name
<< "4. Sort by last name.\n" //sorts by last name
<< "5. Sort by email.\n" //sorts by email
<< "6. Sort by gpa.\n" // sorts by gpa
<< "7. Exit.\n"; //exit the program
}
void readFile(int & count, stdRec Stud[], stdRec *pStud[])
{
ifstream myfile; // text file is called "recordsample"
myfile.open(("recordsample.txt"));
if (!myfile)
{
cout << "Cannot open file, terminating program." << endl;
exit(1);
}
while (!myfile.eof() && count < MAX_SIZE)
{
myfile >> Stud[count].id >> Stud[count].fname >> Stud[count].lname
>> Stud[count].email >> Stud[count].gpa;
pStud[count] = &Stud[count];
count++;
}
myfile.close();
}
void printFile(int count, stdRec *pStud[])
{
cout << pStud[count]->id << "\t" << pStud[count]->fname << "\t"
<< pStud[count]->lname << "\t" << pStud[count]->email << "\t"
<< pStud[count]->gpa << endl;
count++;
}
recordsample.txt
7196478 Mary Jones mary.jones@gmail.com 3.9
3939724 John Lee john.lee@gmail.com 3.5
0943567 Ashley Smith ashley.smith@gmail.com 2.9
2374598 Mark Williams mark.williams@gmail.com 3.3