1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::stringstream;
using std::ofstream;
struct Student {
int idnum;
string last;
string first;
float gpa;
};
Student gStudentList[] = {
{456, "Ames", "Jeremy", 3.45f},
{438, "Coburn", "Barbara", 2.51f},
{321, "Collins", "James", 3.88f},
{322, "Eccelston", "Karen", 3.91f},
{832, "Finney", "Robert", 1.23f},
};
char kDelimiter(',');
// Pack a single student record into a stringstream
void Student_write(Student& student, stringstream& outRecord)
{
outRecord << student.idnum << kDelimiter
<< student.last << kDelimiter
<< student.first << kDelimiter
<< student.gpa;
}
// Use a stringstream to obtain a single student record
void Student_read(Student& student, stringstream& inRecord)
{
std::string chunk;
std::getline(inRecord, chunk, kDelimiter);
student.idnum = atoi(chunk.c_str());
std::getline(inRecord, student.last, kDelimiter);
std::getline(inRecord, student.first, kDelimiter);
std::getline(inRecord, chunk);
student.gpa = atof(chunk.c_str());
}
// store all student records as a text file
void StudentFile_store(string& fileName, Student gStudentList[], int studentCount)
{
std::ofstream fileOut;
fileOut.open(fileName); // Open File for Writing
stringstream recordToWrite; // Write Data to File
Student_write(gStudentList[0],recordToWrite);
// Loop Here
for (int studentCount = 1; studentCount <
fileOut << recordToWrite.str() << endl;
fileOut.close(); // Close Up File
}
void StudentFile_restore(string& fileName)
{
std::ifstream fileIn(fileName);
if (!fileIn.is_open()) {
cout << "Can't open file!: " << fileName << endl;
return;
}
string line;
while (fileIn.good()) { // This Tests that if the File is good then it will get the getline and put it into line so the Record can call it
getline(fileIn, line);
stringstream record;
record << line;
Student test;
Student_read(test, record);
}
fileIn.close();
}
int main()
{
return EXIT_SUCCESS;
}
|