Hello I am creating a program that has the user enter a ssn based on a text file and then it reports that information and calculates the mean of a grade.
I am struggling to understand how I can allow the user to directly add data to the text file based on a series of questions.
The text file uses this format.
111-11-1111
John Doe
G
85 90 87 95 89
111-11-1112
Jane Doe
P
78 65 71 74 75
111-11-1113
John Smith
G
45.0 43.0 44.0 45.0 43.0
#include<iostream>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main() {
int selection = 0;
char goagain;
bool again = true;
ifstream fin;
ofstream fout;
string SSNFind, SSN, name, attendance, trash;
int Lab, PA, Quiz, Midterm, Final;
;
cout << "********** GRADE SYSTEM ************" << endl << endl;
while (again) {
while (selection > 4 || selection < 1)
{
cout << setw(30) << left << "1. Add a record" << endl;
cout << setw(30) << left << "2. Find a person by SSN" << endl;
cout << setw(30) << left << "3. Display all records" << endl;
cout << setw(30) << left << "4. Exit " << endl;
cout << "MAKE A CHOICE" << endl;
cin >> selection;
}
switch (selection)
{
case 1:
break;
case 2:
fin.open("data.txt", ios::in);
//check
cout << "what SSN do you want to find? ";
cin >> SSNFind;
getline(fin, SSN);
while (!fin.eof())
{
getline(fin, name);
getline(fin, attendance);
fin >> Lab >> PA >> Quiz >> Midterm >> Final;
getline(fin, trash);
if (SSN == SSNFind)
{
cout << left << setw(12) << SSN << setw(25) << name << setw(3) << attendance << Final;
}
getline(fin, SSN);
}
fin.close();
break;
case 3:
cout << "Display" << endl;
break;
default:
cout << "exit";
exit(1);
break;
}
cout << "again?(Y or N)";
cin >> goagain;
if (toupper(goagain) == 'Y')
{
again = true;
selection = 0;
}
else
{
again = false;
exit(1);
}
}
}
CodePudding user response:
I'm not 100% sure I understand your problem, but if you want to append data to a file, you should open in in "append" mode, instead of "in"/"out" mode:
fin.open("data.txt", ios::in);
to:
fin.open("data.txt", std::ios::app);
see details: https://en.cppreference.com/w/cpp/io/basic_fstream/open
CodePudding user response:
I wanted to post this as a comment because I'm not sure if this is really an answer.
If you want to append to the end of the file you would open the file in append mode as suggested by Thomas Matthews above.
If you want to insert into the middle or beginning of the file you could open the file in input/output mode and find where you want to insert data at. Then you would buffer from there to the end of the file, return to where you want to insert into file and then write what you need to add then write the buffer back into file. (input/output mode overwrites data in file). If the file is large you should buffer only a portion of the file at a time, two buffers may help here.
Reading from here and looking at the other stream based classes to the left of linked page; I see no way to directly insert into the middle of file without buffering.