I tried the below code to write an object to a dat file:
#include<iostream>
#include<fstream>
#include<string>
#include<string.h>
using namespace std;
class Student
{ //data members
int adm;
string name;
public:
Student()
{
adm = 0;
name = "";
}
Student(int a,string n)
{
adm = a;
name = n;
}
Student setData(Student st) //member function
{
cout << "\nEnter admission no. ";
cin >> adm;
cout << "Enter name of student ";
cin.ignore();
getline(cin,name);
st = Student(adm,name);
return st;
}
void showData()
{
cout << "\nAdmission no. : " << adm;
cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return adm;
}
};
/*
* function to write in a binary file.
*/
void demo()
{
ofstream f;
f.open("student.dat",ios::binary);
for(int i = 0;i<4;i++)
{
Student st;
st = st.setData(st);
f.write((char*)&st,sizeof(st));
}
f.close();
ifstream fin;
fin.open("student.dat",ios::binary);
Student st;
while(!fin.eof())
{
fin.read((char*)&st,sizeof(st));
st.showData();
}
}
int main()
{
demo();
return 0;
}
But when I am executing the demo function I am getting some garbage values from the "student.dat"
file. I am creating a database and want to get the records but I am not able to get all the records in the dat file.
Please suggest a solution
You cannot write complex data types to a file in binary mode. They have some additional variables and functions inside,which you do not know or see. Those data types have some internal state that or context dependent. So, you cannot store in binary and then reuse it somewhere else. That will never work.
The solution is serialization/deserialization.
This sounds complicated, but is not at all in your case. It basically means that all your data from your struct shall be converted to plain text and put in a text-file.
For readin the data back, it will be first read as text, and then converted to your internal data structures.
And the default approach for that is to overwrite the inserter << operator and extractor >> operator.
See the simple example in your modified code:
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
class Student
{ //data members
int adm;
std::string name;
public:
Student()
{
adm = 0;
name = "";
}
Student(int a, std::string n)
{
adm = a;
name = n;
}
Student setData(Student st) //member function
{
std::cout << "\nEnter admission no. ";
std::cin >> adm;
std::cout << "Enter name of student ";
std::getline(std::cin>> std::ws, name);
st = Student(adm, name);
return st;
}
void showData()
{
std::cout << "\nAdmission no. : " << adm;
std::cout << "\nStudent Name : " << name;
}
int retAdmno()
{
return adm;
}
friend std::ostream& operator << (std::ostream& os, const Student& s) {
return os << s.adm << '\n' << s.name << '\n';
}
friend std::istream& operator >> (std::istream& is, Student& s) {
return std::getline(is >> s.adm >> std::ws, s.name);
}
};
/*
* function to write in a binary file.
*/
void demo()
{
std::ofstream f("student.dat");
for (int i = 0; i < 4; i++)
{
Student st;
st = st.setData(st);
f << st;
}
f.close();
std::ifstream fin("student.dat");
Student st;
while (!fin.eof())
{
fin >> st;
st.showData();
}
}
int main()
{
demo();
return 0;
}
Related
I have a class Employees. I'm trying to make the user insert and delete an employee but it's not working. The size of the vectors should be 500.
class Employees{
public:
int maxx = 500;
vector<string> Surname;
vector<string> FirstName;
vector<string> birthdate;
int vacation[500];
public:
Employees() : Surname(500) {}
};
This is the function that inserts, but printing elements of the vectors is not working at all:
void Process(Employees ZZ){
string dateyear;
string datemonth;
string dateday;
int dateyear1;
int datemonth1;
int dateday1;
int Realage;
int Vacationi = 0;
for(int i = 0; i < 500; i++) {
string s;
cin >> s;
string d;
cin >> d;
string c;
cin >> c;
ZZ.Surname.push_back(s);
ZZ.FirstName.push_back(d);
ZZ.birthdate.push_back(c);
cout << endl << ZZ.Surname[1] << endl;
}
Now the delete function, if I input a string then search for it in the vector then get his index then delete, but the vector doesn't update any values.
void DeleteEmployee(Employees ZZ){
cout<< endl << ZZ.Surname[1] << endl ;
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
cout << " delete employee";
string delete1;
cin >> delete1;
auto it = std::find(ZZ.Surname.begin(), ZZ.Surname.end(), delete1);
if (it == ZZ.Surname.end())
{
cout<< " name not in vector " << endl;
}
else
{
//auto index = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_)));
//ZZ.Surname.erase(ZZ.Surname.begin()+index) ;
}
}
This is the main function, also the values of the vector are not printing:
int main()
{
Employees ZZ;
Process(ZZ);
DeleteEmployee(ZZ);
cout << "fyccck";
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
}
There are a lot of things wrong with this code. But the particular issue you are asking about is caused by your functions passing the Employees object by value, so a copy is made, and any changes you make to the copy are not reflected in the original object in main().
You need to change the parameters to pass the Employees object by reference instead:
void Process(Employees &ZZ)
void DeleteEmployee(Employees &ZZ)
That being said, the whole design of the code is not good in general. The vectors are not being kept in sync properly, and for that matter you are using more vectors then you actually need, 1 single vector will suffice. And Process() and DeleteEmployee() should be members of the Employees class, not separate functions. And they are both accessing out-of-bounds of the Surname vector.
I would suggest completely rewriting the code from scratch, for instance something more like this:
struct Employee{
string Surname;
string FirstName;
string BirthDate;
int Vacation;
string DisplayName() const { return Surname + ", " + FirstName; }
};
class Employees{
public:
static const int maxx = 500;
vector<Employee> employees;
Employees() { employees.reserve(maxx); }
bool Add(const Employee &e);
bool Delete(string Surname, string FirstName);
};
bool Employees::Add(const Employee &e) {
if (employees.size() < maxx) {
employees.push_back(e);
return true;
}
return false;
}
bool Employees::Delete(string Surname, string FirstName) {
auto it = std::find_if(employees.begin(), employees.end(),
[&](const Employee &e){
return e.Surname == Surname && e.FirstName == FirstName;
}
);
if (it != employees.end()) {
employees.erase(it);
return true;
}
return false;
}
int main()
{
Employees ZZ;
for(int i = 0; i < Employees::maxx; ++i) {
Employee e;
cin >> e.Surname;
cin >> e.FirstName;
cin >> e.BirthDate;
e.Vacation = 0;//cin >> e.Vacation;
ZZ.Add(e);
cout << endl << e.DisplayName() << endl;
}
cout << " delete employee";
string Surname, FirstName;
if (cin >> Surname >> FirstName) {
if (ZZ.Delete(Surname, FirstName)) {
cout << " name deleted from vector " << endl;
} else {
cout << " name not in vector " << endl;
}
}
cout << "fyccck";
for (auto &e : ZZ.employees) {
cout << e.DisplayName() << endl;
}
return 0;
}
I have recently tried to learn how to create an object of vectors in order to represent objects of students including their names and grades. but when I wrote my program I got some errors regarding using &. I do not know what is the problem with my errors. could you please help me to fix it?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printvector(const vector< student>&); // fill vector.fill in student information
void fillvector(vector< student>&); // print the information of all students
class student {
public:
student();
student(string, char);
~student();
string getName() ;
char getGrade() ;
void setName(string);
void setGrade(char);
private:
string newName;
char newGrade;
};
student::student() { newGrade = ' '; }
student::student(string name, char grade) {
newName = name;
newGrade = grade;
}
student::~student(){ }
string student::getName() { return newName; }
char student::getGrade() { return newGrade; }
void student::setName(string name) { newName = name; }
void student::setGrade(char grade) { newGrade = grade; }
int main() {
vector<student> myclass;
printvector(myclass);
fillvector(myclass);
return 0;
}
void fillvector(vector< student>& newmyclass) {
string name;
char grade;
int classsize;
cout << "how many students are in your class?";
cin >> classsize;
for (int i = 0; i < classsize; i++) {
cout << "enter student name";
cin >> name;
cout << "enter student grade";
cin >> grade;
student newstudent(name, grade);
newmyclass.push_back(newstudent);
cout << endl;
}
}
void printvector( vector< student>& newmyclass) {
unsigned int size = newmyclass.size();
for (unsigned int i = 0; i < size; i++) {
cout << "student name:" << newmyclass[i].getName() << endl;
cout << endl;
cout << "student grade" << newmyclass[i].getGrade() << endl;
cout << endl;
}
}
It seems you're printing your vector before filling it.. Is your problem fixed when you swap them around?
int main() {
vector<student> myclass;
printvector(myclass); // <--- These two lines should probably be swapped
fillvector(myclass); // <---
return 0;
}
I am having trouble reading a file to my class object's members. It says it cannot read the file.
This is my class:
const int SIZE_OF = 5;
class Student
{
public:
Student();
Student(const Student &);
Student(string, int, int, int, int, int);
friend std::istream& operator >> (std::istream& in, Student& S);
void display();
private:
string lastName;
int grades[SIZE_OF];
};
The cpp file associated with my class object to define the functions:
#include "Student.h"
Student::Student()
{
int i;
string lastName = "default";
for (i = 0; i < 5; i++)
{
grades[i] = 0;
}
}
Student::Student(const Student & S)
{
int i;
lastName = S.lastName;
for (i = 0; i < 5; i++)
{
grades[i] = S.grades[i];
}
}
Student::Student(string S, int a, int b, int c, int d, int e)
{
lastName = S;
grades[0] = a;
grades[1] = b;
grades[2] = c;
grades[3] = d;
grades[4] = e;
}
std::istream& operator >> (std::istream& in, Student& S)
{
char dummy;
in >> S.lastName >> S.grades[0]
>> dummy >> S.grades[1]
>> dummy >> S.grades[2]
>> dummy >> S.grades[3]
>> dummy >> S.grades[4];
return in;
}
void Student::display()
{
int i;
int sum = 0;
double average;
cout << "Last Name: " << lastName << endl;
cout << "Grades: " << endl;
for (i = 0; i < 5; i++)
{
cout << grades[i] << endl;
}
for (i = 0; i < 5; i++)
{
sum = sum + grades[i];
}
average = sum / 5;
cout << "Average: " << average;
}
And finally, the main function that I have so far to test the file opening and reading it to the various variables inside the class.
void main()
{
fstream File;
string FileName = "ProgramSixData.txt";
bool FoundFile;
string Line;
Student testStudent;
do {
File.open(FileName, ios_base::in | ios_base::out);
FoundFile = File.is_open();
if (!FoundFile)
{
cout << "Could not open file named " << FileName << endl;
File.open(FileName, ios_base::out); // try to create it
FoundFile = File.is_open();
if (!FoundFile)
{
cout << "Could not create file named " << FileName << endl;
exit(0);
}
else;
}
else;
} while (!FoundFile);
do {
File >> testStudent;
if (File.fail())
{
cout << "Read Failed" << endl;
cout << "Bye" << endl;
exit(0);
}
else;
testStudent.display();
} while (!File.eof());
cout << "Bye" << endl;
File.close();
}
The text document that I am reading from is the following:
George
75,85,95,100,44
Peter
100,100,100,100,100
Frank
44,55,66,77,88
Alfred
99,88,77,66,55
How do I save each of the names and the associated 5 grades to a particular object of the student class?
You are digging too deep. I made an example solution for you, focusing on the parsing. Things could be way shorter and we could instantly make the students instead of doing it the map way, but I want you to understand how to parse the file, because that is obviously what you are struggling with. Ask me anything about the code if you don't understand it.
void main()
{
string FileName = "ProgramSixData.txt";
bool FoundFile;
string Line;
vector<Student> Students;
ifstream file(FileName); //an ifstream is an INPUTstream (same as a fstream with ::in flag. Passing the FileName as argument opens that file
if (file.fail()) //check if the file opened correctly
{
cout << "Failed to open inputfile\n";
return;
}
map <string, vector<int>> studentAndGrades; //map is a container that uses keys and values, every key has a value, we will use the name of the student as the key to access his marks (a vector of int)
vector<string> allLines;
string line;
while (file >> line) //these 2 linessimply reads ALL the lines to the allLines vector
allLines.push_back(line);
for (size_t i = 0; i < allLines.size(); i += 2) //loop over all lines, by 2 at a time (1 for the students name and 1 for his marks)
{
vector<int> numbers;
size_t lastCommaIdx = 0;
size_t currentCount = 0;
string scores(allLines[i + 1]); //make a copy of allLines[i + 1] for convenient use
bool firstLine = true;
for (size_t i = 0; i < scores.size(); ++i) //following code is just to split the numbers from the comma's and put them in a vector of int
{
if (scores[i] == ',')
{
if (firstLine)
{
numbers.push_back(stoi(scores.substr(lastCommaIdx, currentCount)));
firstLine = false;
}
else
{
numbers.push_back(stoi(scores.substr(lastCommaIdx + 1, currentCount)));
}
lastCommaIdx = i;
currentCount = 0;
}
else
{
++currentCount;
}
}
numbers.push_back(stoi(scores.substr(lastCommaIdx + 1))); //last number
studentAndGrades.insert(make_pair(allLines[i], numbers)); //finally, insert them in the map
}
for (const auto& student : studentAndGrades)
Students.push_back(Student(student.first, student.second[0], student.second[1], student.second[2], student.second[3], student.second[4])); //make students from the information that we read into the map
for (auto& student : Students) //display all students with a range based for loop
student.display();
file.close();
}
I wish to output different string for reading variables. For example, below, I wish to print Enter english marks before reading english marks using eng.setmarks(). Please suggest a way to implement this.
Here is my code: (look at for loop below)
#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
class student {
char name[20];
int age;
class marks {
int marks;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
};
public:
marks eng, math, phy, chem, cs; // nested objects are public
void setname( char* n) {
strncpy( name, n, 20);
}
char* getname() {
return name;
}
void setage( int a) {
age = a;
}
float total() {
size_t total = eng.getmarks() + math.getmarks() +
phy.getmarks() + chem.getmarks() + cs.getmarks();
return total/500.0;
}
};
int main() {a
student new_stud;
char temp[20];
cout << "Enter name: ";
cin >> temp;
cin.get( temp, sizeof(temp));
new_stud.setname(temp);
int age;
cout << "Enter age: ";
cin >> age;
new_stud.setage( age);
for( size_t i = 0; i < 5; ++i) {
// I wish to output: "Enter marks in" + subject_name, but harcoding it seems tedious
}
cout << "\nTotal Percentage: " << new_stud.total();
return 0;
}
So if I understand correctly, you would like to print out the name of the variable which you are about to read into. Now this can't be done on the way you want it. The best thing you can do is make an array of subject names, and an array of marks.
string[5] Subjects = {"Maths", "English", "Chemistry", "Physiscs", "Computer Sciences"};
marks[5] Marks;
for(int i=0;i<5;i++) {
cout << "Please enter marks in " << Subjects[i] << ":" << endl;
int a;
cin >> a;
Marks[i].setmarks(a);
}
You could also make the marks class have a field subject name, and give it a function inputfromuser(), like this:
class marks {
int marks;
string subjectName;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
void inputfromuser() {
cout << "Please enter marks in " << subjectName << ":" << endl;
cin >> marks;
}
};
Sorry for me using the std::string type, I am not very comfortable with the raw char[] way to handle texts.
Ok so I figured out and learned a lot of stuff today and I want to thank the community for that. I haven't had any bump in the roads for a few hours now but now I'm stuck.
The last bump in the road. Saving and Loading my program. I have no idea where to start. I looked at how fwrite... and fread... works and all the examples are for programs that aren't split. I don't know where to start with my files. I'll put up 2 functions. If someone can help me how to do save those I can probably figure out the rest.
in gradebook.h
class Student {
public:
string last;
string first;
int student_id;
};
class Course {
public:
string name;
int course_id;
vector <Student> students;
};
class Gradebook {
public:
Gradebook();
void addCourse();
void addStudent();
private:
vector <Course> courses;
};
in gradebook.cpp
void Gradebook::addCourse() {
int i, loop=0;
cout << "Enter Number of Courses: ";
cin >> loop;
for(i=0; i<loop; i++) {
//create newEntry to store variables
Course newEntry;
cout << "Enter Course ID: ";
cin >> newEntry.course_id;
cout << "Enter Course Name: ";
cin >> newEntry.name;
//set variables from newEntry in Courses
courses.push_back(newEntry);
}
}
void Gradebook::addStudent() {
int i, loop=0;
cout << "Enter Number of Students: ";
cin >> loop;
for(i=0; i<loop; i++) {
//create newEntry to store variables
Student newEntry;
cout << "Enter Student ID: ";
cin >> newEntry.student_id;
cout << "Enter Last Name: ";
cin >> newEntry.last;
cout << "Enter First Name: ";
cin >> newEntry.first;
//set variables from newEntry in Students
courses[0].students.push_back(newEntry);
}
}
So if a user was to input some variables in courses and students how would i use fwrite... to save the data?
I wouldn't recommend fwrite, instead look into <fstream>. ifstream, ofstream
Basic saving:
ofstream out("data.txt"); //save file data.txt
out << thedata; //use the << operator to write data
Basic loading:
ifstream in("data.txt"); //reopen the same file
in >> thedata; //use the >> operator to read data.
Here's some sample code that might help without solving the whole thing for you.
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
class Student {
public:
Student()
: student_id(0)
{
}
Student(const std::string &f, const std::string &l, int id)
: first(f)
, last(l)
, student_id(id)
{
}
std::string last;
std::string first;
int student_id;
};
std::ostream &operator <<(std::ostream &os, const Student &s)
{
os << s.last << '\t'
<< s.first << '\t'
<< s.student_id << '\t';
return os;
}
std::istream &operator >>(std::istream &is, Student &s)
{
is >> s.last
>> s.first
>> s.student_id;
return is;
}
bool WriteIt(const std::string &sFileName)
{
std::vector<Student> v;
v.push_back(Student("Andrew", "Bogut", 1231));
v.push_back(Student("Luc", "Longley", 1232));
v.push_back(Student("Andrew", "Gaze", 1233));
v.push_back(Student("Shane", "Heal", 1234));
v.push_back(Student("Chris", "Anstey", 1235));
v.push_back(Student("Mark", "Bradtke", 1236));
std::ofstream os(sFileName);
os << v.size();
for (auto s : v)
os << s;
return os.good();
}
bool ReadIt(const std::string &sFileName)
{
std::ifstream is(sFileName);
int nCount(0);
is >> nCount;
if (is.good())
{
std::vector<Student> v(nCount);
for (int i = 0; i < nCount && is.good(); ++i)
is >> v[i];
if (is.good())
for (auto s : v)
std::cout << s << std::endl;
}
return is.good();
}
int main()
{
const std::string sFileName("Test.dat");
return !(WriteIt(sFileName) && ReadIt(sFileName));
}
Bonus points if you recognise who my "students" are. :-)