Need help resolving an Unhandled Exception Error - c++

I've been learning to program for a few months now and I've been working on a program to manage student data. Here's the code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
class Student
{
private:
string name;
string course;
int section;
int grade;
public:
void calcgrade();
void getData();
void showData();
};
void Student::calcgrade()
{
if (grade >= 90)
grade = 'A';
else if (grade >= 80)
grade = 'B';
else if (grade >= 70)
grade = 'C';
else if (grade >= 60)
grade = 'D';
else
grade = 'F';
}
void Student::getData()
{
cout << "Enter the name of the student: ";
cin.ignore();
getline(cin, name);
cout << "Enter the course: ";
cin >> course;
cout << "Enter the section: ";
cin >> section;
cout << "Enter the grade received: ";
cin >> grade;
calcgrade();
}
void Student::showData()
{
cout << ".......Student Information......" << endl;
cout << "Student Name: " << name << endl;
cout << "Course: " << course << endl;
cout << "Section: " << section << endl;
cout << "Grade: " << grade << endl;
cout << endl;
}
void addData()
{
Student st;
ofstream fout;
fout.open("Student.data", ios::binary | ios::out |
ios::app);
st.getData();
fout.write((char*)& st, sizeof(st));
fout.close();
cout << "Data Successfully Saved to File." << endl;
}
void displayData()
{
Student st;
ifstream file;
file.open("Student.data", ios::in | ios::binary);
if (file.is_open())
{
while (file.read((char*)& st, sizeof(st)))
{
st.showData();
}
cout << "Finished Reading Data From File." <<
endl;
}
else
{
cout << "Unable to open file" << endl;
}
file.close();
}
void searchData()
{
Student st;
ifstream file;
file.open("Student.data", ios::in | ios::binary);
string search;
cout << "Please enter the first name of a student to search for: ";
cin >> search;
bool isFound = 0;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < search.size(); i++)
{
if (temp[i] == search[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
cout << "The name " << search << " was found in the database." << endl;
break;
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
file.close();
}
void modifyData()
{
Student st;
string stname;
bool isFound = 0;
int pos;
fstream file;
file.open("Student.data", ios::in | ios::out | ios::binary);
cout << "Enter the name of a student whose data you want to modify: ";
cin >> stname;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < stname.size(); i++)
{
if (temp[i] == stname[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
pos = file.tellg();
cout << "Current Data" << endl;
st.showData();
cout << "Modified Data" << endl;
st.getData();
file.seekg(pos - sizeof(st));
file.write((char*)& st, sizeof(st));
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
file.close();
}
void deleteData()
{
Student st;
string stname;
bool isFound = 0;
ifstream file;
ofstream fout;
file.open("Student.data", ios::in | ios::binary);
fout.open("Temporary.data", ios::out | ios::app | ios::binary);
cout << "Enter the name of a student whose data you want to delete: ";
cin >> stname;
while (file.read((char*)& st, sizeof(st)))
{
string temp = " ";
getline(file, temp);
for (int i = 0; i < stname.size(); i++)
{
if (temp[i] == stname[i])
isFound = 1;
else
{
isFound = 0;
break;
}
}
if (isFound)
{
cout << "Bleh" << endl;
fout.write((char*)& st, sizeof(st));
}
}
if (file.read((char*)& st, sizeof(st)) && (!isFound))
{
cout << "Name not found." << endl;
}
fout.close();
file.close();
remove("Student.data");
rename("Temporary.data", "Student.data");
}
void printData()
{
ifstream file;
file.open("Student.data", ios::in | ios::binary);
if (file.is_open())
{
cout << file.rdbuf();
}
file.close();
}
int main()
{
int num;
do
{
cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
cout << "======================================== ==============\n";
cout << "0. Close Program. " << endl;
cout << "1. Add Data. " << endl;
cout << "2. List Data. " << endl;
cout << "3. Modify Data. " << endl;
cout << "4. Search For Data. " << endl;
cout << "5. Print Data. " << endl;
cout << "6. Delete Data. " << endl;
cout << "Choose an option: ";
cin >> num;
if (num == 1)
{
addData();
}
else if (num == 2)
{
displayData();
}
else if (num == 3)
{
modifyData();
}
else if (num == 4)
{
searchData();
}
else if (num == 5)
{
printData();
}
else if (num == 6)
{
deleteData();
}
} while (num > 0);
return 0;
}
Ideally, when the program runs, the user chooses an option, with different function calls depending on the number entered. The Add Data option works fine, but when choosing others, such as List Data or Search Data, I run into an error such as: Unhandled exception thrown: read access violation. _Pnext was 0x10A6A04.
Code in xmemory:
inline void _Container_base12::_Orphan_all() noexcept {
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy != nullptr) { // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (_Iterator_base12** _Pnext = &_Myproxy->_Myfirstiter; *_Pnext != nullptr;
*_Pnext = (*_Pnext)->_Mynextiter) {
(*_Pnext)->_Myproxy = nullptr;
}
_Myproxy->_Myfirstiter = nullptr;
}
Given there are no obvious errors in the code, I'd like a little help in figuring out what I've done wrong.

Related

Why can't I delete list object in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I tried my best to figure this out but it was unsuccessful :C
PROBLEM
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
FULL CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <list>
#include <ctime>
using namespace std;
struct Treniruote
{
string data, laikas, vardas, pavarde, pratimai;
};
void NuskaitytiIsFailo(list<Treniruote>& treniruotes)
{
string line, word;
fstream file("planas.csv", ios::in);
if (file.is_open())
{
while (getline(file, line))
{
stringstream str(line);
Treniruote row;
if (getline(str, word, ','))
row.data = word;
if (getline(str, word, ','))
row.laikas = word;
if (getline(str, word, ','))
row.vardas = word;
if (getline(str, word, ','))
row.pavarde = word;
if (getline(str, word, ','))
row.pratimai = word;
treniruotes.push_back(row);
}
}
else
cout << "Could not open the file";
}
void rastiKlientoInfo(list<Treniruote>& treniruotes)
{
int a;
string fname, pavarde;
cout << "Write clients surname:";
cin >> pavarde;
cout << "Output to the screen press -1\n";
cout << "Output to the file press - 2\n";
cout << "Output all exercise needed to be done in a week - 3\n";
cout << "Your choice:";
cin >> a;
if (a == 2)
{
cout << "Enter the file name: ";
cin >> fname;
}
else if (a == 3)
{
cout << "Enter the file name: ";
cin >> fname;
}
else
{
}
for (Treniruote& t : treniruotes)
{
if (t.pavarde == pavarde)
{
if (a == 1)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
else if (a == 3)
{
fstream file(fname + ".csv", ios::app);
file << t.pratimai << endl;
}
else
{
fstream file(fname + ".csv", ios::app);
file << t.data << endl;
file << t.laikas << endl;
file << t.vardas << endl;
file << t.pavarde << endl;
file << t.pratimai << endl;
file << endl;
}
}
}
}
void PakeistiReiksmes(list<Treniruote>& treniruotes)
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti duomenys" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >>duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >>duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
t.vardas = t.pavarde = t.pratimai = "obolys";
}
}
}
}
void SukurtiTuscius(list<Treniruote> &treniruotes)
{
for (int i = 27; i <= 30; ++i)
{
stringstream diena;
diena << "2022.11." << i;
for (int j = 8; j <= 19; ++j)
{
stringstream valanda;
valanda << j << ":00-"<< j+1 <<":00";
Treniruote t;
t.data = diena.str();
t.laikas = valanda.str();
t.vardas = t.pavarde = t.pratimai = "nera";
treniruotes.push_back(t);
}
}
}
void ParodytiVisaTvarkarasti(list<Treniruote>& treniruotes)
{
for (Treniruote& t : treniruotes)
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
void salinti_pridėti(list<Treniruote>& treniruotes)
{
}
void ProgramosPabaiga(list<Treniruote>& treniruotes)
{
fstream file("planas.csv", ios::out);
for (Treniruote& t : treniruotes)
{
file << t.data <<","<< t.laikas << "," << t.vardas << "," << t.pavarde << "," << t.pratimai;
file << endl;
}
cout << "PROGRAMA BAIGTA";
exit(0);
}
int main()
{
int choice;
bool gameOn = true;
list<Treniruote> treniruotes;
struct tm newtime;
time_t now = time(0);
localtime_s(&newtime,&now);
auto month = to_string(1 + newtime.tm_mon);
auto day = to_string(newtime.tm_mday);
auto hour = to_string(newtime.tm_hour);
auto hour_pridėta = to_string(1 + newtime.tm_hour);
//sukuria .csv faila pagal irasyta pavadinima
//string fname;
//cout << "Enter the file name: ";
//cin >> fname;
// fstream file(fname + ".csv", ios::app);
//Menu
while (gameOn != false) {
cout << "*******************************\n";
cout << " 1 - Create empty weekly plan.\n";
cout << " 2 - Show the full schedule.\n";
cout << " 3 - Read the weekly work plan.\n";
cout << " 4 - Change the schedule field information.\n";
cout << " 5 - Find the given client's full weekly workouts\n";
cout << " 7 - Exit.\n";
cout << "*******************************\n";
for (Treniruote& t : treniruotes)
{
if (t.data == "2022." + month + "." + day)
{
if (t.laikas == hour + ":00-" + hour_pridėta + ":00")
{
cout << t.data << endl;
cout << t.laikas << endl;
cout << t.vardas << endl;
cout << t.pavarde << endl;
cout << t.pratimai << endl;
cout << endl;
}
}
}
cout << "*******************************\n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
SukurtiTuscius(treniruotes);
break;
case 2:
ParodytiVisaTvarkarasti(treniruotes);
break;
case 3:
NuskaitytiIsFailo(treniruotes);
break;
case 4:
PakeistiReiksmes(treniruotes);
break;
case 5:
rastiKlientoInfo(treniruotes);
break;
case 6:
{
string duotasLaikas, duotaData;
cout << "irasykite norima data ir laika ,kada norite pakeisti langeli" << endl;
cout << "data(formatas(XXXX.XX.XX)):";
cin >> duotaData;
cout << endl;
cout << "laikas(formatas(XX:XX-XX:XX)):";
cin >> duotasLaikas;
for (Treniruote& t : treniruotes)
{
if (t.data == duotaData)
{
if (t.laikas == duotasLaikas)
{
treniruotes.remove(t);
}
}
}
}
break;
case 7:
{
ofstream file;
file.open("planas.csv", std::ofstream::out | std::ofstream::trunc);
file.close();
ProgramosPabaiga(treniruotes);
break;
}
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
return 0;
}
You must not remove items from a list while iterating through a range-based for loop. Under the hood, the loop stores a begin and end iterator of the original list, and iterate all items between them, and attempting to remove items during the loop will make end unreachable.
Instead, you could simply use std::list::remove_if to remove all elements that satisfy a certain condition:
my_list.remove_if([a, b](const auto& element){
return element.a == a && element.b == b;
};

How to delete stored data in a text file?

The code below was modified based on my original one to fix an error thanks to #RemyLebeau.
It woks great but a new issue have showed up where when I want to delete a student data using option 4 from the menu, after entering their ID, it says their data is deleted but its not. And at the end of the console the message "error reading data from file", under the Standard Error Stream (cerr), keeps showing up. And all my tries to fix it failed.
error_display
//Project on Student Management
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Course
{
string courseName;
string grade;
string status;
};
class Student
{
int id;
int year;
float cgpa;
vector<Course> courses;
string academic_advisor;
public:
Student();
void getData();
void showData() const;
int getID() const { return id; }
friend ostream& operator<<(ostream &out, const Student &s);
friend istream& operator>>(istream &in, Student &s);
};
void writeStr(ostream &out, const string &str)
{
size_t size = str.size();
out.write((char*)&size, sizeof(size));
if (size)
out.write(str.c_str(), size);
}
void readStr(istream &in, string &str)
{
str.clear();
size_t size;
if (in.read((char*)&size, sizeof(size)))
{
if (size > 0)
{
str.resize(size);
in.read(&str[0], size);
}
}
}
ostream& operator<<(ostream &out, const Course &c)
{
writeStr(out, c.courseName);
writeStr(out, c.grade);
writeStr(out, c.status);
return out;
}
istream& operator>>(istream &in, Course &c)
{
readStr(in, c.courseName);
readStr(in, c.grade);
readStr(in, c.status);
return in;
}
ostream& operator<<(ostream &out, const Student &s)
{
out.write((char*)&s.id, sizeof(s.id));
out.write((char*)&s.year, sizeof(s.year));
out.write((char*)&s.cgpa, sizeof(s.cgpa));
writeStr(out, s.academic_advisor);
size_t NumberOfcourses = s.courses.size();
out.write((char*)&NumberOfcourses, sizeof(NumberOfcourses));
for(int i = 0; i < NumberOfcourses; ++i)
{
if (!(out << s.courses[i]))
break;
}
return out;
}
istream& operator>>(istream &in, Student &s)
{
s.courses.clear();
in.read((char*)&s.id, sizeof(s.id));
in.read((char*)&s.year, sizeof(s.year));
in.read((char*)&s.cgpa, sizeof(s.cgpa));
readStr(in, s.academic_advisor);
size_t NumberOfcourses;
if (in.read((char*)&NumberOfcourses, sizeof(NumberOfcourses)))
{
s.courses.reserve(NumberOfcourses);
Course c;
for(size_t i = 0; i < NumberOfcourses; ++i)
{
if (in >> c)
s.courses.push_back(c);
else
break;
}
}
return in;
}
Student::Student()
{
id = 0;
year = 0;
cgpa = 0.0f;
}
void Student::getData()
{
courses.clear();
cout << "\n\nEnter Student Details......\n";
cout << "Enter ID No. : "; cin >> id;
cout << "Enter Intake Year of the Student: "; cin >> year;
cout << "Enter number of Taken courses: ";
size_t NumberOfcourses;
cin >> NumberOfcourses;
cin.ignore();
courses.reserve(NumberOfcourses);
Course c;
for(int a = 0; a < NumberOfcourses; ++a)
{
cout << "\nEnter Subject Name: ";
getline(cin, c.courseName);
cout << "Enter Grade of Subject: ";
getline(cin, c.grade);
cout << "Enter Subject Status: ";
getline(cin, c.status);
courses.push_back(c);
}
cout << "Enter student CGPA: ";
cin >> cgpa;
cin.ignore();
cout << endl;
cout << "Enter Name of Academic Advisor of Student: ";
getline(cin, academic_advisor);
}
void Student::showData() const
{
cout << "\n\n.......Student Details......\n";
cout << "ID No. : " << id << endl;
cout << "Intake Year : " << year << endl;
cout << "Subjects Taken in Previous Semester : " << endl;
for(size_t t = 0; t < courses.size(); ++t)
{
cout << "\t" << courses[t].courseName << ": " << courses[t].grade << " (" << courses[t].status << ") ";
cout << endl;
}
cout << "CGPA : " << cgpa << endl;
cout << "Name of academic advisor of Student : " << academic_advisor << endl;
cout << endl;
}
void addData()
{
Student s;
s.getData();
ofstream fout("Students.txt", ios::binary|ios::app);
if (fout << s)
cout << "\n\nData Successfully Saved to File....\n";
else
cerr << "\n\nError Saving Data to File!\n";
}
void displayData()
{
ifstream fin("Students.txt", ios::binary);
Student s;
while (fin >> s)
{
s.showData();
}
if (fin)
cout << "\n\nData Reading from File Successfully Done....\n";
else
cerr << "\n\nError Reading Data from File!\n";
}
void searchData()
{
int n;
cout << "Enter ID Number you want to search for : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Details of ID No. " << n << " are: \n";
s.showData();
flag = true;
break;
}
}
if (fin)
{
if (!flag)
cout << "The ID No. " << n << " not found....\n\n";
cout << "\n\nData Reading from File Successfully Done....\n";
}
else
cerr << "\n\nError Reading Data from File!\n";
}
void deleteData()
{
int n;
cout << "Enter ID Number you want to delete : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
ofstream tout("TrashStud.txt", ios::binary|ios::app);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " has been deleted:\n";
s.showData();
tout << s;
flag = true;
}
else
{
fout << s;
}
}
if (fin)
{
if (fout)
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("tempStud.txt");
}
else
{
remove("Students.txt");
rename("tempStud.txt", "Students.txt");
cout << "\n\nData Successfully Deleted from File....\n";
}
}
else
{
cerr << "\n\nError Saving Data to File!\n";
}
}
else
{
cerr << "\n\nError Reading Data from File!\n";
}
}
void modifyData()
{
int n;
cout << "Enter ID Number you want to Modify : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " will be modified with new data:\n";
s.showData();
cout << "\n\nNow Enter the New Details....\n";
s.getData();
flag = true;
}
fout << s;
}
if (fin)
{
if (fout)
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("TempStud.txt");
}
else
{
remove("Students.txt");
rename("TempStud.txt", "Students.txt");
cout << "\n\nData Successfully Updated in File....\n";
}
}
else
{
cerr << "\n\nError Saving Data to File!\n";
}
}
else
{
cerr << "\n\nError Reading Data from File!\n";
}
}
void project()
{
int ch;
do
{
system("cls");
cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
cout << "====================SEGI University=================\n";
cout << "0. Exit from Program\n";
cout << "1. Write Data to File\n";
cout << "2. Read Data From File\n";
cout << "3. Search Data From File\n";
cout << "4. Delete Data From File\n";
cout << "5. Modify Data in File\n";
cout << "Enter your choice : ";
cin >> ch;
system("cls");
switch (ch)
{
case 1: addData(); break;
case 2: displayData(); break;
case 3: searchData(); break;
case 4: deleteData(); break;
case 5: modifyData(); break;
}
system("pause");
}
while (ch != 0);
}
int main()
{
project();
}
The error is because fin ( in deleteData () function) runs till the end of file , and at the end fin stores nullptr(boolean conversion to false) that is why else statement runs.And its obvious that why the while loop breaks .
for checking if the file is open or not you can use if(fin.is_open()) for fin and similarly for fout like if(fout.is_open())

How to display all the data I entered into my text file?

The following is a code to enter some details of students into a text file and from the main menu, the user can display them using option 2.
My problem is in the section where it should display all the "Taken Courses by student".
When I choose to display all data, the "mentioned section using the for loop only display the last value I enter when writing to the file.
How can I make it display all my entries?
The issue is under the showdata and displaydata functions.
//Project on Student Management
#include<iostream>
#include<fstream>
#include<iomanip>
#include<stdlib.h>
using namespace std;
class Student
{
int id;
int year;
char grade[50];
float cgpa;
int NumberOfcourses;
char courseName[100];
char academic_advisor[100];
char status[100];
public:
void getData();
void showData();
int getID(){return id;}
}s;
void Student::getData()
{
cout<<"\n\nEnter Student Details......\n";
cout<<"Enter ID No. : "; cin>>id;
cout << "Enter Intake Year of the Student: "; cin >> year;
cout << "Enter number of Taken courses: ";
cin >> NumberOfcourses;
for(int a=1; a<=s.NumberOfcourses; a++)
{
cout<<"\nEnter Subject Name: ";
cin.ignore();
cin.getline(courseName, 100);
cout << "Enter Grade of Subject: ";
cin >> grade;
cout<<"\nEnter Subject Status: ";
cin.ignore();
cin.getline(status, 100);
}
cout << "Enter student CGPA: ";
cin >> s.cgpa;
cout << endl;
cout << "Enter Name of Academic Advisor of Student: "; cin.ignore();
cin.getline(s.academic_advisor, 100);
}
void Student::showData()
{
cout << "\n\n.......Student Details......\n";
cout << "ID No. : " << id << endl;
cout << "Intake Year : " << year << endl;
cout << "Subjects Taken in Previous Semester : " << endl;
for(int t=1; t<=NumberOfcourses; t++)
{
cout << "\t" << courseName << ": " << grade << " ("<< status << ") ";
cout << endl;
}
cout << "CGPA : " << cgpa << endl;
cout << "Name of academic advisor of Student : " << academic_advisor << endl;
cout << endl;
}
void addData()
{
ofstream fout;
fout.open("Students.txt", ios::out|ios::app);
s.getData();
fout.write((char*)&s,sizeof(s));
fout.close();
cout<<"\n\nData Successfully Saved to File....\n";
}
void displayData()
{
ifstream fin;
fin.open("Students.txt",ios::in);
while(fin.read((char*)&s,sizeof(s)))
{
s.showData();
}
fin.close();
cout<<"\n\nData Reading from File Successfully Done....\n";
}
void searchData()
{
int n, flag=0;
ifstream fin;
fin.open("Students.txt",ios::in);
cout<<"Enter ID Number you want to search for : ";
cin>>n;
while(fin.read((char*)&s,sizeof(s)))
{
if(n==s.getID())
{
cout<<"The Details of ID No. "<<n<<" are: \n";
s.showData();
flag++;
}
}
fin.close();
if(flag==0)
cout<<"The ID No. "<<n<<" not found....\n\n";
cout<<"\n\nData Reading from File Successfully Done....\n";
}
void deleteData()
{
int n, flag=0;
ifstream fin;
ofstream fout,tout;
fin.open("Students.txt",ios::in);
fout.open("TempStud.txt",ios::out|ios::app);
tout.open("TrashStud.txt",ios::out|ios::app);
cout<<"Enter ID Number you want to delete : ";
cin>>n;
while(fin.read((char*)&s,sizeof(s)))
{
if(n==s.getID())
{
cout<<"The Following ID No. "<< n <<" has been deleted:\n";
s.showData();
tout.write((char*)&s,sizeof(s));
flag++;
}
else
{
fout.write((char*)&s,sizeof(s));
}
}
fout.close();
tout.close();
fin.close();
if(flag==0)
cout<<"The ID No. "<< n <<" not found....\n\n";
remove("Students.dat");
rename("tempStud.txt","Students.txt");
}
void modifyData()
{
int n, flag=0, pos;
fstream fio;
fio.open("Students.txt", ios::in|ios::out);
cout<<"Enter ID Number you want to Modify : ";
cin>>n;
while(fio.read((char*)&s,sizeof(s)))
{
pos=fio.tellg();
if(n==s.getID())
{
cout<<"The Following ID No. "<<n<<" will be modified with new data:\n";
s.showData();
cout<<"\n\nNow Enter the New Details....\n";
s.getData();
fio.seekg(pos-sizeof(s));
fio.write((char*)&s,sizeof(s));
flag++;
}
}
fio.close();
if(flag==0)
cout<<"The ID No. "<<n<<" not found....\n\n";
}
void project()
{
int ch;
do
{
system("cls");
cout<<"...............STUDENT MANAGEMENT SYSTEM..............\n";
cout<<"======================================================\n";
cout<<"0. Exit from Program\n";
cout<<"1. Write Data to File\n";
cout<<"2. Read Data From File\n";
cout<<"3. Search Data From File\n";
cout<<"4. Delete Data From File\n";
cout<<"5. Modify Data in File\n";
cout<<"Enter your choice : ";
cin>>ch;
system("cls");
switch(ch)
{
case 1: addData(); break;
case 2: displayData(); break;
case 3: searchData(); break;
case 4: deleteData(); break;
case 5: modifyData(); break;
}
system("pause");
}while(ch);
}
int main()
{
project();
}
Console Display with problem
Your Student class can only hold 1 set of course information. Your getData() loop is overwriting the same variables over and over, that is why you only see the last course entered. You need to allocate an array (or better, use a std::vector) to hold multiple courses per Student.
There are other problems with your code as well.
Try something more like this instead:
//Project on Student Management
#include <iostream>
#include <fstream>
using namespace std;
struct Course
{
char courseName[100];
char grade[50];
char status[100];
};
class Student
{
int id;
int year;
float cgpa;
int NumberOfcourses;
Course *courses;
char academic_advisor[100];
public:
Student();
~Student();
void getData();
void showData() const;
int getID() const { return id; }
friend ostream& operator<<(ostream &out, const Student &s);
friend istream& operator>>(istream &in, Student &s);
};
ostream& operator<<(ostream &out, const Course &c)
{
out.write(c.courseName, sizeof(c.courseName));
out.write(c.grade, sizeof(c.grade));
out.write(c.status, sizeof(c.status));
return out;
}
istream& operator>>(istream &in, Course &c)
{
in.read(c.courseName, sizeof(c.courseName));
in.read(c.grade, sizeof(c.grade));
in.read(c.status, sizeof(c.status));
return in;
}
ostream& operator<<(ostream &out, const Student &s)
{
out.write((char*)&s.id, sizeof(s.id));
out.write((char*)&s.year, sizeof(s.year));
out.write((char*)&s.cgpa, sizeof(s.cgpa));
out.write(s.academic_advisor, sizeof(s.academic_advisor));
out.write((char*)&s.NumberOfcourses, sizeof(s.NumberOfcourses));
for(int i = 0; i < s.NumberOfcourses; ++i)
{
out << s.courses[i];
}
return out;
}
istream& operator>>(istream &in, Student &s)
{
delete[] s.courses;
s.courses = NULL;
s.NumberOfcourses = 0;
in.read((char*)&s.id, sizeof(s.id));
in.read((char*)&s.year, sizeof(s.year));
in.read((char*)&s.cgpa, sizeof(s.cgpa));
in.read(s.academic_advisor, sizeof(s.academic_advisor));
int NumberOfcourses;
if (in.read((char*)&NumberOfcourses, sizeof(NumberOfcourses)))
{
s.courses = new Course[NumberOfcourses];
for(int i = 0; i < NumberOfcourses; ++i)
{
if (in >> s.courses[i])
s.NumberOfcourses++;
else
break;
}
}
return in;
}
Student::Student()
{
id = 0;
year = 0;
cgpa = 0.0f;
NumberOfcourses = 0;
courses = NULL;
academic_advisor[0] = '\0';
}
Student::~Student()
{
delete[] courses;
}
void Student::getData()
{
cout << "\n\nEnter Student Details......\n";
cout << "Enter ID No. : "; cin >> id;
cout << "Enter Intake Year of the Student: "; cin >> year;
cout << "Enter number of Taken courses: ";
cin >> NumberOfcourses;
cin.ignore();
delete[] courses;
courses = new Course[NumberOfcourses];
for(int a = 0; a < NumberOfcourses; ++a)
{
cout << "\nEnter Subject Name: ";
cin.getline(courses[a].courseName, 100);
cout << "Enter Grade of Subject: ";
cin.getline(courses[a].grade, 50);
cout << "\nEnter Subject Status: ";
cin.getline(courses[a].status, 100);
}
cout << "Enter student CGPA: ";
cin >> cgpa;
cin.ignore();
cout << endl;
cout << "Enter Name of Academic Advisor of Student: ";
cin.getline(academic_advisor, 100);
}
void Student::showData() const
{
cout << "\n\n.......Student Details......\n";
cout << "ID No. : " << id << endl;
cout << "Intake Year : " << year << endl;
cout << "Subjects Taken in Previous Semester : " << endl;
for(int t = 0; t < NumberOfcourses; ++t)
{
cout << "\t" << courses[t].courseName << ": " << courses[t].grade << " (" << courses[t].status << ") ";
cout << endl;
}
cout << "CGPA : " << cgpa << endl;
cout << "Name of academic advisor of Student : " << academic_advisor << endl;
cout << endl;
}
void addData()
{
Student s;
s.getData();
ofstream fout("Students.txt", ios::binary|ios::app);
if (fout << s)
cout << "\n\nData Successfully Saved to File....\n";
else
cerr << "\n\nError Saving Data to File!\n";
}
void displayData()
{
ifstream fin("Students.txt", ios::binary);
Student s;
while (fin >> s)
{
s.showData();
}
if (!fin)
cerr << "\n\nError Reading Data from File!\n";
else
cout << "\n\nData Reading from File Successfully Done....\n";
}
void searchData()
{
int n;
cout << "Enter ID Number you want to search for : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Details of ID No. " << n << " are: \n";
s.showData();
flag = true;
break;
}
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else
{
if (!flag)
cout << "The ID No. " << n << " not found....\n\n";
cout << "\n\nData Reading from File Successfully Done....\n";
}
}
void deleteData()
{
int n;
cout << "Enter ID Number you want to delete : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
ofstream tout("TrashStud.txt", ios::binary|ios::app);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " will be deleted:\n";
s.showData();
tout << s;
flag = true;
}
else
{
fout << s;
}
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else if (!fout)
{
cerr << "\n\nError Saving Data to File!\n";
}
else
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("tempStud.txt");
}
else
{
remove("Students.txt");
rename("tempStud.txt", "Students.txt");
cout << "\n\nData Successfully Deleted from File....\n";
}
}
}
void modifyData()
{
int n;
cout << "Enter ID Number you want to Modify : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " will be modified with new data:\n";
s.showData();
cout << "\n\nNow Enter the New Details....\n";
s.getData();
flag = true;
}
fout << s;
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else if (!fout)
{
cerr << "\n\nError Saving Data to File!\n";
}
else
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("TempStud.txt");
}
else
{
remove("Students.txt");
rename("TempStud.txt", "Students.txt");
cout << "\n\nData Successfully Updated in File....\n";
}
}
}
void project()
{
int ch;
do
{
system("cls");
cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
cout << "======================================================\n";
cout << "0. Exit from Program\n";
cout << "1. Write Data to File\n";
cout << "2. Read Data From File\n";
cout << "3. Search Data From File\n";
cout << "4. Delete Data From File\n";
cout << "5. Modify Data in File\n";
cout << "Enter your choice : ";
cin >> ch;
system("cls");
switch (ch)
{
case 1: addData(); break;
case 2: displayData(); break;
case 3: searchData(); break;
case 4: deleteData(); break;
case 5: modifyData(); break;
}
system("pause");
}
while (ch != 0);
}
int main()
{
project();
}
Alternatively:
//Project on Student Management
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Course
{
string courseName;
string grade;
string status;
};
class Student
{
int id;
int year;
float cgpa;
vector<Course> courses;
string academic_advisor;
public:
Student();
void getData();
void showData() const;
int getID() const { return id; }
friend ostream& operator<<(ostream &out, const Student &s);
friend istream& operator>>(istream &in, Student &s);
};
void writeStr(ostream &out, const string &str)
{
size_t size = str.size();
out.write((char*)&size, sizeof(size));
if (size)
out.write(str.c_str(), size);
}
void readStr(istream &in, string &str)
{
str.clear();
size_t size;
if (in.read((char*)&size, sizeof(size)))
{
if (size > 0)
{
str.resize(size);
in.read(&str[0], size);
}
}
}
ostream& operator<<(ostream &out, const Course &c)
{
writeStr(out, c.courseName);
writeStr(out, c.grade);
writeStr(out, c.status);
return out;
}
istream& operator>>(istream &in, Course &c)
{
readStr(in, c.courseName);
readStr(in, c.grade);
readStr(in, c.status);
return in;
}
ostream& operator<<(ostream &out, const Student &s)
{
out.write((char*)&s.id, sizeof(s.id));
out.write((char*)&s.year, sizeof(s.year));
out.write((char*)&s.cgpa, sizeof(s.cgpa));
writeStr(out, s.academic_advisor);
size_t NumberOfcourses = s.courses.size();
out.write((char*)&NumberOfcourses, sizeof(NumberOfcourses));
for(int i = 0; i < NumberOfcourses; ++i)
{
if (!(out << s.courses[i]))
break;
}
return out;
}
istream& operator>>(istream &in, Student &s)
{
s.courses.clear();
in.read((char*)&s.id, sizeof(s.id));
in.read((char*)&s.year, sizeof(s.year));
in.read((char*)&s.cgpa, sizeof(s.cgpa));
readStr(in, s.academic_advisor);
size_t NumberOfcourses;
if (in.read((char*)&NumberOfcourses, sizeof(NumberOfcourses)))
{
s.courses.reserve(NumberOfcourses);
Course c;
for(size_t i = 0; i < NumberOfcourses; ++i)
{
if (in >> c)
s.courses.push_back(c);
else
break;
}
}
return in;
}
Student::Student()
{
id = 0;
year = 0;
cgpa = 0.0f;
}
void Student::getData()
{
courses.clear();
cout << "\n\nEnter Student Details......\n";
cout << "Enter ID No. : "; cin >> id;
cout << "Enter Intake Year of the Student: "; cin >> year;
cout << "Enter number of Taken courses: ";
size_t NumberOfcourses;
cin >> NumberOfcourses;
cin.ignore();
courses.reserve(NumberOfcourses);
Course c;
for(int a = 0; a < NumberOfcourses; ++a)
{
cout << "\nEnter Subject Name: ";
getline(cin, c.courseName);
cout << "Enter Grade of Subject: ";
getline(cin, c.grade);
cout << "\nEnter Subject Status: ";
getline(cin, c.status);
s.courses.push_back(c);
}
cout << "Enter student CGPA: ";
cin >> cgpa;
cin.ignore();
cout << endl;
cout << "Enter Name of Academic Advisor of Student: ";
getline(cin, academic_advisor);
}
void Student::showData() const
{
cout << "\n\n.......Student Details......\n";
cout << "ID No. : " << id << endl;
cout << "Intake Year : " << year << endl;
cout << "Subjects Taken in Previous Semester : " << endl;
for(size_t t = 0; t < courses.size(); ++t)
{
cout << "\t" << courses[t].courseName << ": " << courses[t].grade << " (" << courses[t].status << ") ";
cout << endl;
}
cout << "CGPA : " << cgpa << endl;
cout << "Name of academic advisor of Student : " << academic_advisor << endl;
cout << endl;
}
void addData()
{
Student s;
s.getData();
ofstream fout("Students.txt", ios::binary|ios::app);
if (fout << s)
cout << "\n\nData Successfully Saved to File....\n";
else
cerr << "\n\nError Saving Data to File!\n";
}
void displayData()
{
ifstream fin("Students.txt", ios::binary);
Student s;
while (fin >> s)
{
s.showData();
}
if (!fin)
cerr << "\n\nError Reading Data from File!\n";
else
cout << "\n\nData Reading from File Successfully Done....\n";
}
void searchData()
{
int n;
cout << "Enter ID Number you want to search for : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Details of ID No. " << n << " are: \n";
s.showData();
flag = true;
break;
}
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else
{
if (!flag)
cout << "The ID No. " << n << " not found....\n\n";
cout << "\n\nData Reading from File Successfully Done....\n";
}
}
void deleteData()
{
int n;
cout << "Enter ID Number you want to delete : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
ofstream tout("TrashStud.txt", ios::binary|ios::app);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " will be deleted:\n";
s.showData();
tout << s;
flag = true;
}
else
{
fout << s;
}
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else if (!fout)
{
cerr << "\n\nError Saving Data to File!\n";
}
else
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("tempStud.txt");
}
else
{
remove("Students.txt");
rename("tempStud.txt", "Students.txt");
cout << "\n\nData Successfully Deleted from File....\n";
}
}
}
void modifyData()
{
int n;
cout << "Enter ID Number you want to Modify : ";
cin >> n;
ifstream fin("Students.txt", ios::binary);
ofstream fout("TempStud.txt", ios::binary);
Student s;
bool flag = false;
while (fin >> s)
{
if (n == s.getID())
{
cout << "The Following ID No. " << n << " will be modified with new data:\n";
s.showData();
cout << "\n\nNow Enter the New Details....\n";
s.getData();
flag = true;
}
fout << s;
}
if (!fin)
{
cerr << "\n\nError Reading Data from File!\n";
}
else if (!fout)
{
cerr << "\n\nError Saving Data to File!\n";
}
else
{
fin.close();
fout.close();
if (!flag)
{
cout << "The ID No. " << n << " not found....\n\n";
remove("TempStud.txt");
}
else
{
remove("Students.txt");
rename("TempStud.txt", "Students.txt");
cout << "\n\nData Successfully Updated in File....\n";
}
}
}
void project()
{
int ch;
do
{
system("cls");
cout << "...............STUDENT MANAGEMENT SYSTEM..............\n";
cout << "======================================================\n";
cout << "0. Exit from Program\n";
cout << "1. Write Data to File\n";
cout << "2. Read Data From File\n";
cout << "3. Search Data From File\n";
cout << "4. Delete Data From File\n";
cout << "5. Modify Data in File\n";
cout << "Enter your choice : ";
cin >> ch;
system("cls");
switch (ch)
{
case 1: addData(); break;
case 2: displayData(); break;
case 3: searchData(); break;
case 4: deleteData(); break;
case 5: modifyData(); break;
}
system("pause");
}
while (ch != 0);
}
int main()
{
project();
}

Difficulties with saving a text file using ofstream

Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.

Searching an array for number of occurrences

This code is supposed to display a menu with 6 options. create new file, display numbers, total, and average, display a sort, search for a num and tell yow how many occurrences it had, append random numbers, and display largest.
It runs and does MOST of what it is supposed to do but I just CANNOT get the searchNum function to search for the number entered.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);
int main()
{
int choice = 0;
string myFileName = "";
do
{
cout << "** MENU **" << endl << endl;
cout << "Current Data File: ";
cout << fixed << setprecision(2) << showpoint;
menu();
cin >> choice;
while (choice < 1 || choice > 7)
{
cout << "Menu Choice: ";
cin >> choice;
cout << endl;
}
switch (choice)
{
case 1:
myFileName = createFile();
break;
case 2:
displayNumTotalAverage(myFileName);
break;
case 3:
displaySortedNums(myFileName);
break;
case 4:
searchNum(myFileName);
break;
case 5:
displayLargestNum(myFileName);
break;
case 6:
appendRandomNum(myFileName);
break;
}
} while (choice != 7);
system("PAUSE");
return 0;
}
void menu()
{
cout << "\n\n(1) Select / create data file(.txt file extension will be added automatically)\n"
<< "(2) Display all numbers, total, and average\n(3) Display all numbers sorted\n(4) "
<< "Search for a number and display how many times it occurs\n(5) Display the largest number\n"
<< "(6) Append a random number(s)\n(7) Exit the program\n\nMenu Choice:";
}
string createFile()
{
string myFileName;
ifstream inFile;
cout << "\nName of data file: ";
cin >> myFileName;
inFile.open(myFileName);
if (inFile)
{
cout << myFileName;
}
else
{
cout << "\nFile not found, creating file.\n\n";
ofstream outFile;
outFile.open(myFileName + ".txt");
}
system("PAUSE");
return myFileName;
}
void displayNumTotalAverage(string myFileName)
{
ifstream inFile;
const int SIZE = 50;
int num[SIZE];
int count = 0;
int total = 0;
double average = 0;
inFile.open(myFileName + ".txt");
while (!inFile)
cout << "\nData File is empty" << endl << endl;
while (count < SIZE && inFile >> num[count])
count++;
inFile.close();
for (int index = 0; index < count; index++)
{
cout << num[index] << endl;
total += num[index];
}
average = (float)total / count;
cout << endl << "Total : " << total << endl << endl;
cout << "Average: " << average << endl << endl;
cout << "File Successfully Read" << endl << endl;
system("PAUSE");
return;
}
void displaySortedNums(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
if(inFile.good())
{
const int SIZE = 50;
int num[SIZE]; int counter = 0;
while (counter < SIZE && inFile >> num[counter])
counter++;
inFile.close();
for(int idx1 = 0; idx1 < counter; ++idx1)
for(int idx2 = idx1; idx2 < counter; ++idx2)
if(num[idx1] > num[idx2])
{
int tmp = num[idx1];
num[idx1] = num[idx2];
num[idx2] = tmp;
}
for (int i = 0; i < counter; i++)
{
cout << num[i] << endl;
}
cout << endl;
}
system("PAUSE");
return;
}
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
const int SIZE = 50;
int num[SIZE];
bool found = false;
int position = -1;
int index = 0;
int userNum = 0;
int counter = 0;
int numCount = 0;
cout << "Search Number: ";
cin >> userNum;
cout << endl << endl;
while (index < SIZE && !found)
{
if (num[index] == userNum)
{
found = true;
position = index;
numCount++;
}
index++;
}
cout << userNum << " occurs " << numCount << " times ";
cout << "File Successfully Read\n\n";
system("PAUSE");
return;
}
void displayLargestNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int nums[SIZE];
int count = 0;
int highest;
while (count < SIZE && inFile >> nums[count])
count++;
highest = nums[0];
for (int i = 0; i < SIZE; i++)
{
if (nums[i] > highest)
highest = nums[count];
}
cout << "\nLargest Number: " << highest << endl << "File Successfully Read" << endl << endl;
}
void appendRandomNum(string myFileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int num = 0;
int count = 0;
ofstream outFile;
outFile.open(myFileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
system("PAUSE");
return;
}
Can anyone please help with this?
I can see 2 problems in searchNum function:
The file is opened but num array is not populated with the file content
numCount will always return either 0 or 1. Remove 'found' boolean variable altogether and it will then return the correct numCount value.
Here are some important rules they never seem to teach in programming courses: start with something small and simple that works, add complexity a little at a time, and develop new functionality in isolation.
Suppose you have the rest of the code working perfectly, and you can produce a file called nums.txt that looks like this:
7
9
3
8
0
2
4
8
3
9
Now you want to develop and test the searchNum function. So you write a main function like this:
int main()
{
string myFileName = "nums";
searchNum(myFileName);
system("PAUSE");
return 0;
}
Then a searchNum function:
void searchNum(string myFileName)
{
}
You compile and run this, it does nothing, so far so good.
Now have it open the file, read the first number and display it:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
inFile >> num;
cout << num << endl;
}
So far so good. Now iterate through the whole file:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
while(inFile >> num)
{
cout << num << endl;
}
}
So far so good. Now count the 8's:
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + "txt");
int num;
int count = 0;
while(inFile >> num)
{
cout << num << endl;
if(num == 8)
++count;
}
}
You get the idea. Using this approach you'll get clean working code, and you'll get it faster than by trying to write it all and then fix all the bugs.
A couple of things I noticed also in searchNum
inFile.open(myFileName + "txt"); should be inFile.open(myFileName + ".txt");, a dot is missing from the suffix.
Read the rest of the answers and get acquainted with the debugger it will save you a lot of time and frustration.
Here is your code sample with the needed corrections. Keep up the good work and invest some time for the use of a debugger.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
//Function Prototypes
void menu();
string createFile();
void displayNumTotalAverage(string myFileName);
void displaySortedNums(string myFileName);
void searchNum(string myFileName);
void displayLargestNum(string myFileName);
void appendRandomNum(string myFileName);
int main()
{
int choice = 0;
string myFileName = "";
do
{
cout << "** MENU **" << endl << endl;
cout << "Current Data File: " << myFileName << (!myFileName.empty() ? ".txt" : "");
cout << fixed << setprecision(2) << showpoint;
menu();
cin >> choice;
while (choice < 1 || choice > 7)
{
cout << "Menu Choice: ";
cin >> choice;
cout << endl;
}
switch (choice)
{
case 1:
myFileName = createFile();
break;
case 2:
displayNumTotalAverage(myFileName);
break;
case 3:
displaySortedNums(myFileName);
break;
case 4:
searchNum(myFileName);
break;
case 5:
displayLargestNum(myFileName);
break;
case 6:
appendRandomNum(myFileName);
break;
}
} while (choice != 7);
cin.get();
return 0;
}
void menu()
{
cout << "\n\n(1) Select / create data file(.txt file extension will be added automatically)\n"
<< "(2) Display all numbers, total, and average\n(3) Display all numbers sorted\n(4) "
<< "Search for a number and display how many times it occurs\n(5) Display the largest number\n"
<< "(6) Append a random number(s)\n(7) Exit the program\n\nMenu Choice:";
}
string createFile()
{
string myFileName;
ifstream inFile;
cout << "\nName of data file: ";
cin >> myFileName;
inFile.open(myFileName + ".txt", std::ifstream::in);
if (inFile)
{
cout << myFileName;
}
else
{
cout << "\nFile not found, creating file.\n\n";
ofstream outFile;
outFile.open(myFileName + ".txt");
outFile.close();
}
cin.get();
return myFileName;
}
void displayNumTotalAverage(string myFileName)
{
ifstream inFile;
const int SIZE = 50;
int num[SIZE];
int count = 0;
int total = 0;
double average = 0;
inFile.open(myFileName + ".txt");
while (!inFile)
cout << "\nData File is empty" << endl << endl;
while (count < SIZE && inFile >> num[count])
count++;
inFile.close();
for (int index = 0; index < count; index++)
{
cout << num[index] << endl;
total += num[index];
}
average = (float)total / count;
cout << endl << "Total : " << total << endl << endl;
cout << "Average: " << average << endl << endl;
cout << "File Successfully Read" << endl << endl;
cin.get();
return;
}
void displaySortedNums(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
if(inFile.good())
{
const int SIZE = 50;
int num[SIZE]; int counter = 0;
while (counter < SIZE && inFile >> num[counter])
counter++;
inFile.close();
for(int idx1 = 0; idx1 < counter; ++idx1)
for(int idx2 = idx1; idx2 < counter; ++idx2)
if(num[idx1] > num[idx2])
{
int tmp = num[idx1];
num[idx1] = num[idx2];
num[idx2] = tmp;
}
for (int i = 0; i < counter; i++)
{
cout << num[i] << endl;
}
cout << endl;
}
cin.get();
return;
}
void searchNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int num[SIZE];
int position = -1;
int index = 0;
int userNum = 0;
int counter = 0;
int numCount = 0;
cout << "Search Number: ";
cin >> userNum;
cout << endl << endl;
// Fill num array with inFile numbers.
while (counter < SIZE && inFile >> num[counter++]);
while (index < SIZE)
{
if (num[index] == userNum)
{
position = index;
numCount++;
}
index++;
}
cout << userNum << " occurs " << numCount << " times ";
cout << "File Successfully Read\n\n";
cin.get();
return;
}
void displayLargestNum(string myFileName)
{
ifstream inFile;
inFile.open(myFileName + ".txt");
const int SIZE = 50;
int nums[SIZE];
int count = 0;
int highest;
while (count < SIZE && inFile >> nums[count])
count++;
highest = nums[0];
for (int i = 0; i < SIZE; i++)
{
if (nums[i] > highest)
highest = nums[count];
}
cout << "\nLargest Number: " << highest << endl << "File Successfully Read" << endl << endl;
}
void appendRandomNum(string myFileName)
{
cout << "i am in the appendRandomNum function - option 6" << endl;
int count = 0;
ofstream outFile;
outFile.open(myFileName + ".txt", ios::app);
cout << "How many random numbers: ";
cin >> count;
for (int i = 0; i < count; i++)
outFile << rand() % 10 << endl;
outFile.close();
cout << endl << "Number(s) Added" << endl << endl;
cin.get();
return;
}