The code goes like this:
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "\nRoll no : ";
cin >> roll;
cout << "\nMarks : ";
cin >> marks;
cout << "\n";
}
void display(void)
{
cout << "\n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.\n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "\n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
s1.display();
}
fil.close();
getch();
}
The program is about to read and write details of a student using classes.
error
The output shows the details twice if i enter the details once.
output found
nitin, rollno 12 has 98% marks.
nitin, rollno 12 has 98% marks.
output expected
nitin, rollno 12 has 98% marks.
Try this :
class student
{
char name[20];
int roll;
float marks;
public:
void getdata(void)
{
char ch;
cin.get(ch);
cout << "Name : ";
cin.getline(name, 20);
cout << "\nRoll no : ";
cin >> roll;
cout << "\nMarks : ";
cin >> marks;
cout << "\n";
}
void display(void)
{
cout << "\n" << name << " ,roll no " << roll << " has " << marks
<< "% marks.\n";
}
int getroll()
{ return roll; }
};
void main()
{
clrscr();
student s1;
fstream fil;
int rn;
char ans = 'y';
fil.open("stu.dat", ios::out);
while (ans == 'y')
{
s1.getdata();
fil.write((char *)&s1, sizeof(s1));
cout << "\n Do you want to enter more records :?";
cin >> ans;
}
fil.close();
fil.open("stu.dat", ios::in);
fil.seekg(0);
while (fil)
{
fil.read((char *)&s1, sizeof(s1));
if (feof(fil)) {
puts ("End-of-File reached.");
break;
}
s1.display();
}
fil.close();
getch();
}
Related
In the code I shared below, I want to output vector data type in the AddStoreCustomer() section. This is how the code works. But there is a bug in the code. If I enter a single word in the customer variable, the code works fine. But when I enter two words in this variable with a space between them,the code doesn't work.
#include <iostream>
#include <vector>
using namespace std;
class Store {
int StoreID;
string StoreName;
string StoreCity;
string StoreTown;
string StoreTel;
vector <string> StoreCustomer;
public:
Store(){}
Store(int sid, string sname, string scity, string stown, string stel, string scustomer) {
setStoreID(sid);
setStoreName(sname);
setStoreCity(scity);
setStoreTown(stown);
setStoreTel(stel);
setStoreCustomer(scustomer);
}
void setStoreID(int sid) {
StoreID = sid;
}
void setStoreName(string sname) {
StoreName = sname;
}
void setStoreCity(string scity) {
StoreCity = scity;
}
void setStoreTown(string stown) {
StoreTown = stown;
}
void setStoreTel(string stel) {
StoreTel = stel;
}
void setStoreCustomer(string scustomer) {
StoreCustomer.push_back(scustomer);
}
int getStoreID() {
return StoreID;
}
string getStoreName() {
return StoreName;
}
string getStoreCity() {
return StoreCity;
}
string getStoreTown() {
return StoreTown;
}
string getStoreTel() {
return StoreTel;
}
vector <string> getStoreCustomer() {
return StoreCustomer;
}
~Store(){}
};
Store s2[50];
void AddStore() {
int id, menu;
string name, city, town, tel;
for (int i = 0; i < 1; i++) {
cout << "Lutfen Magaza ID Numarasini Girin: ";
cin >> id;
s2[i].setStoreID(id);
cout << "Lutfen Magaza Adini Girin: ";
cin >> name;
s2[i].setStoreName(name);
cout << "Lutfen Magazanin Bulundugu Ili Girin: ";
cin >> city;
s2[i].setStoreCity(city);
cout << "Lutfen Magazanin Bulundugu Ilceyi Girin: ";
cin >> town;
s2[i].setStoreTown(town);
cout << "Lutfen Magazanin Telefon Numarasini Girin: ";
cin >> tel;
s2[i].setStoreTel(tel);
cout << "Magaza Eklendi" << endl;
cout << "\n\n";
}
cout << "Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else {
cout << "Tanımlanamayan Giris!!!" << endl;
//Menu();
}
}
int Search2(const int& y) {
for (int j = 0; j < 100; j++) {
if (s2[j].getStoreID() == y)
return j;
}
return -1;
}
void AddStoreCustomer() {
int id, found, menu;
string customer;
cout << "Lutfen Musteri Eklemek Istediginiz Magazanin ID Numarasini Girin:";
cin >> id;
found = Search2(id);
if (found == -1)
{
cout << "Magaza Bulunamadi" << endl;
}
else {
cout << "Magaza Bulundu.\n" << "Lutfen Magaza Veri Tabanina Eklemek Istediginiz Musterinin Bilgilerini Girin: ";
cin >> customer;
s2[found].setStoreCustomer(customer);
cout << "Girilen Musteri Bilgisi Secilen Magazaya Eklendi";
cout << "Magaza ID: " << s2[found].getStoreID() << "\n Magaza Adi: " << s2[found].getStoreName() << "\n Magazanin Bulundugu Il: " << s2[found].getStoreCity() << "\n Magazanin Bulundugu Ilce:" << s2[found].getStoreTown() << "\n Magaza Iletisim Numarasi: " << s2[found].getStoreTel() << endl;
cout << "Musteriler: " << endl;
for (int i = 0; i < s2[found].getStoreCustomer().size(); i++)
{
cout << "\t\t" << s2[found].getStoreCustomer()[i] << endl;
}
}
cout << "Tekrar Giris Yapmak icin 1 Menuye Donmek icin 0 " << endl;
cin >> menu;
if (menu == 0) {
StoreMenu();
}
else if (menu == 1) {
AddStoreCustomer();
}
This happens because you are using cin>> to read input, which reads until the first whitespace symbol. If you want to read a whole line, consider using std::getline() instead:
getline(cin, customer);
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();
}
I am creating a program that will write and read the content of a binary file. The part I am struggling with is reading/writing pointsEarned and studentGPA as a double. It prints out 6.36599e-314 instead of the number I provided. I looked around the web for a solution but couldn't find one, so here I am.
class student {
int studentID;
char name[30];
char lastName[30];
double pointsEarned;
double studentGPA;
public:
void getData() {
cout << "\nEnter the Student ID: ";
cin >> studentID;
cout << "\n\nEnter the first name of the student: ";
cin >> name;
cout << "\n\nEnter the last name of the student: ";
cin >> lastName;
cout << "\n\nEnter the amount of points earned by the student: ";
cin >> pointsEarned;
cout << "\n\nEnter the Student GPA: ";
cin >> studentGPA;
}
void showData() {
cout << "\nStudent ID: " << studentID;
cout << "\nStudent Name: " << name << " " << lastName;
cout << "\nPoints: " << pointsEarned;
cout << "\nGPA: " << studentGPA << "\n";
}
int studentNumber() {
return studentID;
}
};
//input student info into the dat file
void write() {
student object;
student val;
ofstream file2;
file2.open("student.dat", ios::binary | ios::app);
object.getData();
file2.write((char *)&object, sizeof(object));
file2.close();
}
void display() {
student object;
ifstream file1;
file1.open("student.dat", ios::binary);
if (!file1) {
cout << "File not Found!\n";
}
else {
//read data
while (file1.read((char *)&object, sizeof(object))) {
object.showData();
}
}
file1.close();
}
//display student information through their studentID
void search(int n) {
student object;
ifstream file1;
file1.open("student.dat", ios::binary);
if (!file1) {
cout << "File not Found!\n";
}
else {
while (file1.read((char *)&object, sizeof(object))) {
if (object.studentNumber() == n)
object.showData();
//validation
if (object.studentNumber() != n) {
cout << "StudentID doesn't exist\n";
break;
}
}
}
file1.close();
}
//delete student
void deleteRecord(int n) {
student object;
//open both files
ifstream file1;
file1.open("student.dat", ios::binary);
ofstream file2;
file2.open("Temp.dat", ios::out|ios::binary);
//write contents of f1 to f2
while (file1.read((char*)&object, sizeof(object))) {
if (object.studentNumber() != n)
file2.write((char*)&object, sizeof(object));
}
file1.close();
file2.close();
//delete original file and rename the new one
remove("student.dat");
rename("Temp.dat", "student.dat");
}
void editRecord(int n) {
fstream fp;
student object;
int found = 0;
fp.open("student.dat", ios::in | ios::out);
while (fp.read((char *)&object, sizeof(object)) && found == 0) {
if (object.studentNumber() == n) {
object.showData();
cout << "\nEnter The New Details of student";
object.getData();
int pos = -1 * sizeof(object);
fp.seekp(pos, ios::cur);
fp.write((char*)&object, sizeof(object));
found = 1;
}
//validation
if (object.studentNumber() != n) {
cout << "StudentID doesn't exist\n";
break;
}
}
fp.close();
}
int main() {
int n;
int studentIDNumber;
cout << " Press 1 if you choose to input student information\n Press 2 to display all student's information\n Press 3 to display a specific student's information\n Press 4 to modify student information\n Press 5 to delete a student\n";
cin >> n;
if (n == 1) {
write();
} else if(n == 2){
display();
}
else if (n == 3) {
cout << "Enter the Student ID to get the student information: ";
cin >> studentIDNumber;
search(studentIDNumber);
}
else if (n == 4) {
cout << "Enter the Student ID to modify the student information: ";
cin >> studentIDNumber;
editRecord(studentIDNumber);
}
else if (n == 5) {
deleteRecord(studentIDNumber);
cout << "The record has been deleted.\n";
}
else {
cout << "Error. The number is neither 1 or 2. Please try again. \n";
}
return 0;
}
The output:
Student ID: 55
Student Name: John Doe
Points: 6.36599e-314
GPA: 7.27464e+199
Press any key to continue . . .
I am having a hard time figuring this out. Everything else in my project is working so far, but when I try to add to my array of objects, it crashes. I get an error of cannot read string. This is the message, I have tried so many things. Here is the error, and it crashes after the input on the SetNewAccountInfo() function. I am new to programming, and hope this code is formatted on here right. This is a school project so I'm not asking for the answer, maybe just explain why I am unable to add to my array in laymen terms. Pointers and such are confusing so far.
static _Elem *__CLRCALL_OR_CDECL copy(_Elem *_First1, const _Elem *_First2, size_t _Count)
{ // copy [_First2, _First2 + _Count) to [_First1, ...)
**return (_Count == 0 ? _First1** : (_Elem *)_CSTD memcpy(_First1, _First2, _Count));
}
// TestClassC.cpp : main project file.
#include "stdafx.h"
#include "BankClassType.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
void MainMenu(BankClassType bo[],int num, int cAcct);
void AcctOptionsMenu(BankClassType bo[], int num, int cAcct);
int SetNewAccountInfo();
void PrintAccountInfo();
void AccountDeposit();
void AccountWithdrawal();
int main()
{
const int num = 4;
BankClassType *bo = new BankClassType[num];
BankClassType b;
BankClassType bo0("12345", 'P', "Gates", "Bill", 175253.99, 6875250.23);
BankClassType bo1("12346", 'R', "Jones", "Tommy", 845.21, 2700.00);
BankClassType bo2("12347", 'P', "Asimov", "Isaac", 300.67, 14750.29);
bo[0] = bo0;
bo[1] = bo1;
bo[2] = bo2;
int cAcct = 3;
b.MainMenu(bo, num, cAcct);
_getch();
return 0;
}
//BankClassType.h File
#pragma once
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
#ifndef BankClassType_h
#define BankClassType_h
using namespace std;
class BankClassType
{
private:
string AccountNumber;
string FirstName;
string LastName;
double CheckingBalance;
double SavingsBalance;
char AccountType;
public:
BankClassType()
{
FirstName = "";
LastName = "";
AccountNumber = "";
AccountType = 'p';
CheckingBalance = 0;
SavingsBalance = 0;
}
BankClassType(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal);
//~BankClassType();
void SetNewAccountInfo(BankClassType bo[], int num, int cAcct);
void PrintAccountInfo();
void AccountDeposit(BankClassType bo[], int number, int num, int cAcct);
void AccountWithdrawal(BankClassType bo[], int number, int num, int cAcct);
void AcctOptionsMenu(BankClassType bo[], int num, int cAcct);
void MainMenu(BankClassType bo[], int num, int cAcct);
//void ExistingAccounts(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal);
string getAccountNumber()
{
return AccountNumber;
}
char getAccountType()
{
return AccountType;
}
double getCheckingBalance(double amount)
{
CheckingBalance = CheckingBalance + amount;
return CheckingBalance;
}
double getSavingsBalance(double amount)
{
SavingsBalance = SavingsBalance + amount;
return SavingsBalance;
}
double getWithdrawalCheckingBalance(double amount)
{
CheckingBalance = CheckingBalance - amount;
return CheckingBalance;
}
double getWithdrawalSavingsBalance(double amount)
{
SavingsBalance = SavingsBalance - amount;
return SavingsBalance;
}
string getFirstName()
{
return FirstName;
}
string getLastName()
{
return LastName;
}
};
#endif
//BankClassImp.cpp
#include "stdafx.h"
#include "BankClassType.h"
#include <iostream>
#include <conio.h>
#include <string>
#include <ostream>
using namespace std;
BankClassType::BankClassType(string acctNumber, char acctType, string lname, string fname, double cBal, double sBal)
{
AccountNumber = acctNumber;
AccountType = acctType;
LastName = lname;
FirstName = fname;
CheckingBalance = cBal;
SavingsBalance = sBal;
/*cout << "\nName: " << LastName << ", " << FirstName;
cout << "\nAccountNumber: " << AccountType << AccountNumber;
cout << "\nChecking Balance: " << CheckingBalance;
cout << "\nSavings Balance: " << SavingsBalance<<endl;
*/
}
/*BankClassType::~BankClassType()
{
delete[] FirstName;
delete[] LastName;
delete[] AccountNumber;
delete[] AccountType;
}*/
void BankClassType::SetNewAccountInfo(BankClassType bo[], int num, int cAcct)
{
//BankClassType * bt = new BankClassType;
BankClassType c;
string fName;
string acctNum;
string lName;
char accType;
double cBal, sBal;
if (cAcct >= 5)
{
"Sorry the accounts are currently full, press any key to return to main menu: ";
c.MainMenu(bo, num, cAcct);
_getch();
}
else
cout << "\nEnter the 5 digit account number: "; cin >> acctNum;
cout << "\nEnter the account type (p) or (r): "; cin >> accType;
cout << "\nEnter the first name: "; cin >> fName;
cout << "\nEnter the last name: "; cin >> lName;
cout << "\nEnter the checking balance: "; cin >> cBal;
cout << "\nEnter the savings balance: "; cin >> sBal;
BankClassType bo3(acctNum, accType, lName, fName, cBal, sBal);
bo[cAcct + 1] = bo3;
}
void BankClassType::PrintAccountInfo()
{
cout << "Name: " << LastName << ", " << FirstName;
cout << "\nAccountNumber: " << AccountType << AccountNumber;
cout << "\nChecking Balance: " << CheckingBalance;
cout << "\nSavings Balance: " << SavingsBalance << endl << endl;
}
void BankClassType::AccountDeposit(BankClassType bo[], int number, int num, int cAcct)
{
int choice;
BankClassType b;
cout << "\nEnter 1 for checking or 2 for savings: ";
cin >> choice;
if (choice == 1)
{
double amount;
cout << "Enter amount to deposit into checking: " << endl;
cin >> amount;
bo[number].getCheckingBalance(amount);
cout << "You added $" << amount << " to checking account number " << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else if (choice == 2)
{
double amount;
cout << "Enter amount to deposit into savings: " << endl;
cin >> amount;
bo[number].getSavingsBalance(amount);
cout << "You added $" << amount << " to savings number" << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else
{
cout << "Incorrect Input, try again: ";
_getch();
AccountDeposit(bo, number, num, cAcct);
}
}
void BankClassType::AccountWithdrawal(BankClassType bo[], int number, int num, int cAcct)
{
int choice;
BankClassType b;
cout << "\nEnter 1 for checking or 2 for savings: ";
cin >> choice;
if (choice == 1)
{
double amount;
cout << "Enter amount to withdrawal from checking: " << endl;
cin >> amount;
bo[number].getWithdrawalCheckingBalance(amount);
cout << "You withdrew $" << amount << " from checking account number " << bo[number].getAccountNumber();
cout << "\nPress any key to return to main menu: ";
_getch();
b.MainMenu(bo, num, cAcct);
}
else if (choice == 2)
{
double amount;
cout << "Enter amount withdrawal from savings: " << endl;
cin >> amount;
bo[number].getWithdrawalSavingsBalance(amount);
cout << "You withdrew $" << amount << " from savings account number " << bo[number].getAccountNumber();
_getch();
b.MainMenu(bo, num, cAcct);
}
else
{
cout << "Incorrect Input, try again";
_getch();
AccountDeposit(bo, number, num, cAcct);
}
}
void BankClassType::MainMenu(BankClassType bo[], int num, int cAcct)
{
cout << "\nWelcome, here are the current accounts on file:\n" << endl;
for (int i = 0; i < cAcct; i++)
{
cout << i + 1 << "--";
bo[i].PrintAccountInfo();
}
int choice;
BankClassType b;
cout << "Enter number (1-5) of account you wish to make changes\n Enter 6 to add an account\nEnter 7 to exit\n --->";
cin >> choice;
if (choice < 6)
b.AcctOptionsMenu(bo, num, cAcct);
else if (choice == 6)
{
bo[cAcct + 1].SetNewAccountInfo(bo, num, cAcct);
cout << "You have successfully added an account!" << endl;
_getch();
cAcct++;
b.MainMenu(bo, num, cAcct);
}
else if (choice == 7)
{
cout << "You have exited, press any key to continue: ";
_getch();
system("cls");
}
else if(choice > 7)
{
cout << "Not a valid input, press a key to try again: ";
_getch();
system("cls");
MainMenu(bo, num, cAcct);
}
}
void BankClassType::AcctOptionsMenu(BankClassType bo[], int num, int cAcct)
{
char choice;
int check = 0;
int count = 0;
int number;
BankClassType b;
while (check == 0) {
cout << "\t\t\n\n" << "Main Menu";
cout << "\t\n\n" << "Select by letter:";
cout << "\t\n" << "(d) - Deposits";
cout << "\t\n" << "(w) - Withdrawals";
cout << "\t\n" << "(s) - Show Account Information.";
cout << "\t\n" << "(q) - Quit Program.\n\n";
cout << "\t" << "Choice: ";
choice = _getche();
switch (choice) {
case 'd':
case 'D':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i +1 << "---" << bo[i].getAccountNumber()<< "\n\n" ;
cin >> number;
bo[number].AccountDeposit(bo,number, num, cAcct);
system("cls");
break;
case 'w':
case 'W':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i + 1<< "---" << bo[i].getAccountNumber() << "\n\n";
cin >> number;
bo[number].AccountWithdrawal(bo, number, num, cAcct);
system("cls");
break;
case 's':
case 'S':
system("cls");
cout << "\nChoose Account:\n ";
for (int i = 0; i < cAcct; i++) cout << i + 1 << "---" << bo[i].getAccountNumber() << "\n\n";
cin >> number;
bo[number].PrintAccountInfo();
_getche();
system("cls");
break;
case 'q':
case 'Q':
check = 1;
break;
default:
cout << "\nInvalid selection. Press a key to return to main menu.";
_getche();
}
if (check == 1)
break;
}
}
It looks like the array allocated in main is too short. You allocate a block of 4 elements, pass '3' as the cAcct, then bo[cAcct + 1] = bo3. The index will be 4 which is one pass the end of the array. Results are undefined and a crash is likely
I am doing a lot of things wrong here. Plz help.
#include <iostream>
#include <fstream>
using namespace std;
class student {
int rno;
char name[15];
float marks;
public:
void getdata()
{
cout << "\nEnter Roll No. : ";
cin >> rno;
cout << "\nEnter Name : ";
cin >> name;
cout << "\nEnter Marks : ";
cin >> marks;
};
void writedata()
{
fstream input;
input.open("stu.dat", ios::out | ios::app);
input.write((char*)this, sizeof(student));
input.close();
};
void readdata()
{
int temp;
cout << "\nEnter roll no: ";
cin >> temp;
fstream output;
output.open("stu.dat", ios::in);
output.seekg(0, ios::beg);
while (output.read((char*)this, sizeof(student))) {
if (rno == temp) {
cout << "\nRoll no. : " << rno
<< "\nName : " << name
<< "\nMarks : " << marks;
}
else {
cout << "\nWrong Roll no entered";
};
};
};
};
int main()
{
student s[25];
student* st;
char ans = 'y', ans2 = 'y', ans3 = 'y';
int o, i = 0, j = 0;
do {
cout << "\nEnter your choice\n1.Write\n2.Read";
cin >> o;
switch (o) {
case 1:
while (ans2 == 'y' || ans2 == 'Y') {
s[i].getdata();
s[i].writedata();
cout << "\nDo you want to continue?";
cin >> ans2;
i++;
};
break;
case 2:
while (ans3 == 'y' || ans3 == 'Y') {
st->readdata();
cout << "\nDo you want to continue?";
cin >> ans3;
j++;
};
break;
};
} while (ans == 'y' || ans == 'Y');
return 0;
}
All seems well until line 82:
st->readdata();
where the variable st is not initialised but used.