c++ program crashing after reading a file the second time - c++

Basically, the problem is already described in the title: When starting the program first time ( meaning that the new file is created then ), it works perfectly and it doesn't crash, but when trying a second time ( meaning that the file already is there ), it crashes.
Question is: Why does it crash and how do I prevent that from happening?
Here's the code:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
class TStudent
{
public:
string Name, Surname;
int Age;
TStudent(string name, string surname, int age)
{
Name = name;
Surname = surname;
Age = age;
cout <<"\n";
}
string toString() const
{
return Name + " ; " + Surname + " ; " + to_string(Age);
}
int aux1 = sizeof(Name), aux2 = sizeof(Surname);
};
class TRegistru
{
public:
string name, surname;
int age;
vector <TStudent> students;
TRegistru(const TStudent &other)
{
this->name = other.Name;
this->surname = other.Surname;
this->age = other.Age;
students.push_back(other);
}
void adauga(const TStudent& student)
{
students.push_back(student);
}
void salveaza(string file_name)// creating the file and storing the data
{
ofstream file1;
file1.open(file_name, ios::app);
file1.write((char*)&students, sizeof(students));
file1.close();
cout<<"\nFile saved and closed successfully.\n"<<endl;
}
void sterge()
{
students.clear();
}
void incarca(string file_name)// opening the file and reading the data
{
ifstream file2;
file2.open(file_name, ios::in);
if(!file2)
{
cout<<"Error in opening file..";
}
else
{
cout<<"File opened successfully.\n"<<endl;
}
file2.seekg(0);
file2.read((char*)&students, sizeof(students));
}
void afiseaza()//printing the data
{
for(auto student : students)
{
cout << student.Name << endl ;
cout << student.Surname << endl;
cout << student.Age << endl;
cout <<"\n";
}
}
string toString() const
{
string ret{};
for(const auto& student : students)
{
ret += student.toString() + "\n";
}
return ret;
}
};
int main()
{
TStudent student1("Simion", "Neculae", 21);
TStudent student2("Elena", "Oprea", 21);
TRegistru registru(student1);
registru.adauga(student2);
registru.salveaza("data.bin");// creating the file and storing the data
registru.sterge();
registru.incarca("data.bin");// opening the file and reading the data
registru.afiseaza();//printing the data
return 0;
}

After reading a second time your code I realised that the way you try to read and write a vector was plain wrong:
vector <TStudent> students;
...
ifstream file2;
file2.open(file_name, ios::in);
file2.seekg(0);
file2.read((char*)&students, sizeof(students)); // WRONG!!!
A vector does store its data in a contiguous way, but the address of the vector is not the address of the data. The correct way is to serialize each element of the vector to the file and then deserialize each element and push that into the vector.

Related

How can I read data from a file into a vector of class without using getLine()?

I have some data in the file that I would like to be able to read into a vector of a class-type/object. This object also has within itself a vector that takes in another class type, and the data that needs to populate that inner vector is also contained within the text file. How can I read the data from the file into the vectors accordingly without using getLine()?
The data is formatted as so in the document.
143 Jones
1234 2 C
-1
123 Smith
4321 4 A
132 3 B
-1
Where the first line is the ID of the student followed by their name, and below it is a series of classes that student has taken followed by the number of credits each course is worth and the grade the student got for the course.
Below is the course class header code
#pragma once
#include <iostream>
class Course {
public:
Course(int, int, std::string);
int getCourseCode() const {return courseCode;}
int getCredits() const {return courseCredits;}
std::string getGrade() const {return grade;}
void print(std::ostream &os) const;
private:
int courseCode;
int courseCredits;
std::string grade;
};
inline std::ostream &operator <<(std::ostream &os, const Course &course) {
course.print(os);
return os;
}
inline Course::Course(int courseCode, int courseCredits, std::string grade) {
this->courseCode = courseCode;
this->courseCredits = courseCredits;
this->grade = grade;
}
Below is the student class header code
#pragma once
#include <vector>
#include "course.h"
class Student {
public:
Student(int, std::string, std::vector<Course> courses);
int getID() const;
double getGPA() const;
std::string getName() const;
void print(std::ostream &os) const;
std::vector<Course> courses;
private:
int id;
std::string name;
};
inline std::ostream &operator << (std::ostream &os, const Student &student) {
student.print(os);
return os;
}
Below is the student.cpp code
#include "student.h"
#include <string>
using namespace std;
Student::Student(int id, std::string name, vector<Course> courses) {
this->id = id;
this->name = name;
this->courses = courses;
}
int Student::getID() const {
return id;
}
string Student::getName() const {
return name;
}
double Student::getGPA() const {
double total;
double creds;
double cgrade;
double gpa;
for(int i = 0; i < courses.size(); i++) {
if(courses[i].getGrade() == "A") cgrade = 4.0;
else if(courses[i].getGrade() == "B") cgrade = 3.0;
else if(courses[i].getGrade() == "C") cgrade = 2.0;
else if(courses[i].getGrade() == "D")cgrade = 1.0;
total += cgrade * courses[i].getCredits();
creds += courses[i].getCredits();
}
gpa = total / creds;
return gpa;
}
void Student::print(std::ostream &os) const {
os << id << " " << name << ": " << this->getGPA() << endl;
for(int i = 0; i < courses.size(); i++) {
os << courses[i];
}
}
This is what I've tried so far in terms of trying to load the vectors
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "student.h"
using namespace std;
void loadStudents(string fileName, vector<Student> &students);
bool compareCourses(const Course &c1, const Course &c2);
bool compareStudents(const Student &s1, const Student &s2);
void printResults(string fileName, vector<Student> &students);
int main() {
try {
vector<Student> students;
loadStudents("students.data", students);
cout << students.size() << " records processed" << endl;
return 0;
}
catch(string message) {
cout << "Error: " << message << endl;
exit(1);
}
};
void loadStudents(string fileName, vector<Student> &students) {
ifstream studentsFile(fileName.c_str());
if(!studentsFile.good()) {
throw string("Input file: " + fileName + ", not found!");
}
int id;
string name;
vector<Course> cs;
while(studentsFile >> id >> name >> cs) {
students.place_back(student);
}
studentsFile.close();
}
bool compareCourses(const Course &c1, const Course &c2) {
return c1.getGrade() < c2.getGrade();
}
bool compareStudents(const Student &s1, const Student &s2) {
return s1.getGPA() < s2.getGPA();
}
void printResults(string fileName, vector<Student> &students) {
ofstream outputFile(fileName.c_str());
if(!outputFile.good()) {
throw string("Output file: " + fileName + ", not found!");
}
for(auto student : students) {
outputFile << student.print(outputFile) << endl;
}
outputFile.close();
}
I'm getting an error stating that "no operator ">>" matches these operands" in the while loop inside the loadStudents function, which I think pertains to the istream for the vector.
The desired output is something like this printed to an output file.
143 Smith: 3.57143
4321 (4 credits): A
132 (3 credits): B
143 Jones: 2
1234 (2 credits): C
2 records processed
Where the student ID and name are printed along with their calculated GPA and the courses they took below them followed by a message stating the number of students that were processed.
My main issue pertains to the loading of the students vector with the subsequent data of the course information being appropriately loaded into the courses vector for each student. Is this possible without using the getLine() method and istream >>?

fread is reading garbage in file

I am working on my assignment and faced a problem with fread() in C++. When I modify the name in my file it modifies it perfectly as I want but the problem occurs when I try to read the file after that, it reads the whole file but it does not stop after that it's running total 146 times whereas there are only 3 names.
My code:-
#include <bits/stdc++.h>
using namespace std;
struct person{
int id;
string fname;
}s;
void write(){
FILE *outfile;
struct person input;
int num,ident;
string sname[] = {"a","b","c"};
outfile = fopen ("C:\\Users\\Amritesh\\Desktop\\students.txt","wb");
if (outfile == NULL)
{
fprintf(stderr, "\nError opend file\n");
exit (1);
}
scanf("%d",&num);
for(int i=0;i<num;i++){
s.fname = sname[i];
cin >> s.id;
fwrite (&s, sizeof(s), 1, outfile);
}
fclose(outfile);
}
void read(){
FILE *file1;
int i=0;
file1 = fopen ("C:\\Users\\Amritesh\\Desktop\\students.txt","r");
while(fread(&s, sizeof(s), 1, file1) == 1) {
cout << "ID " << s.id << " Name " <<s.fname << endl;
}
fclose (file1);
}
void modify(){
FILE *file;
file = fopen ("C:\\Users\\Amritesh\\Desktop\\students.txt","r+");
while(fread(&s, sizeof(s), 1, file)) {
if(s.fname == "a"){
s.fname = "d";
fseek(file,-sizeof(s),SEEK_CUR);
fwrite (&s, sizeof(s), 1,file);
}
}
fclose (file);
}
int main(){
write();
modify();
read();
}
Edited code:-
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct person
{
int id;
string fname;
}s,temp;
void read()
{
int num;
ifstream fin;
fin.open("C:\\Users\\Amritesh\\Desktop\\student.txt",ios::in);
fin.seekg(0,ios::beg);
//scanf("%d",&num);
while(fin){
cout << s.fname << s.id << endl;
}
fin.close();
}
void write(){
int i=0;
ofstream fout;
fout.open("C:\\Users\\Amritesh\\Desktop\\student.txt");
while(i!=2) {
cin >> s.id >> s.fname;
fout << "ID " << s.id << " Name " <<s.fname << endl;
i++;
}
fout.close();
}
void modify(){
fstream mod;
mod.open ("C:\\Users\\Amritesh\\Desktop\\student.txt");
while(mod) {
if(s.fname == "a"){
s.fname = "d";
mod.seekg(-sizeof(s),ios::cur);
mod << s.fname;
}
}
mod.close();
}
int main(){
write();
read();
modify();
}
Thanks for any answer!
Here are three ideas based on our discussion. I'll start with free functions for reading and writing a person object since it looks like you're at that stage right now. I'll move on to adding member functions in your person class and end with adding stream operators for convenience.
An example of free (non-member) read and write functions:
#include <iostream>
#include <string>
#include <fstream>
struct person {
int id;
std::string fname;
};
std::ostream& write(std::ostream& os, const person& p) {
os << p.id << ',' << p.fname << '\n'; // stream out the properties of a person
return os; // look at the next example for an alternative doing the same thing
}
std::istream& read(std::istream& is, person& p) {
// extract "id" and if it succeeds, check if the next char is a , char
if(is >> p.id && is.peek() == ',') {
is.ignore(); // step over the , char
std::getline(is, p.fname); // read the rest of the line into p.fname
} else {
// we didn't get id or the , char, so set the stream in a failed state
is.setstate(is.failbit);
}
return is;
}
int main() {
// write to file
{
std::ofstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test1{10, "Foo Bar"};
person test2{20, "Apa Bepa"};
write(file, test1);
write(file, test2);
}
// read from file
{
std::ifstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test;
while(read(file, test)) {
std::cout << test.fname << '\n';
}
}
}
An example of making read and write member functions in person:
#include <iostream>
#include <string>
#include <fstream>
struct person {
int id;
std::string fname;
std::ostream& write(std::ostream& os) const {
// this does the same thing as in the first example
return os << id << ',' << fname << '\n';
}
std::istream& read(std::istream& is) {
if(is >> id && is.peek() == ',') {
is.ignore(); // step over the , char
std::getline(is, fname);
} else {
is.setstate(is.failbit); // we didn't get id or the , char
}
return is;
}
};
int main() {
// write to file
{
std::ofstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test1{10, "Foo Bar"};
person test2{20, "Apa Bepa"};
test1.write(file);
test2.write(file);
}
// read from file
{
std::ifstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test;
while(test.read(file)) {
std::cout << test.fname << '\n';
}
}
}
Member functions supported by stream operators:
#include <iostream>
#include <string>
#include <fstream>
struct person {
int id;
std::string fname;
std::ostream& write(std::ostream& os) const {
return os << id << ',' << fname << '\n';
}
std::istream& read(std::istream& is) {
if(is >> id && is.peek() == ',') {
is.ignore(); // step over the , char
std::getline(is, fname);
} else {
is.setstate(is.failbit); // we didn't get id or the , char
}
return is;
}
};
// stream operators calling member functions
std::ostream& operator<<(std::ostream& os, const person& p) { return p.write(os); }
std::istream& operator>>(std::istream& is, person& p) { return p.read(is); }
int main() {
// write to file
{
std::ofstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test1{10, "Foo Bar"};
person test2{20, "Apa Bepa"};
file << test1 << test2; // calling operator<< for each person object
}
// read from file
{
std::ifstream file("C:\\Users\\Amritesh\\Desktop\\student.txt");
person test;
while(file >> test) { // extract one person at a time using operator>>
std::cout << test.fname << '\n';
}
}
}

C++ How to load a textfile and adding the content to a class?

I am trying to learn how to use classes and I figured I'd create some sort of supermarket system to aid me with learning. After I have saved all the values from my text file into the temp variables, how do I then use them to create an object? I assume I want one object per item you can "buy"?
If you have any other tips on how to improve my code, please mention them as I just started with C++ a few days ago.
My text file looks like:
42 68 Apples
35 1 Oranges
70 25 Bananas
And my code is below:
// Classes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
class Products {
private:
int price;
int ID;
int quantity;
public:
void setPrice(int newPrice) {
price = newPrice;
}
void setID(int newID) {
ID = newID;
}
void setQuantity(int newQuantity) {
quantity = newQuantity;
}
int getPrice() {
return price;
}
int getID() {
return ID;
}
int getQuantity() {
return quantity;
}
};
int main()
{
std::string line;
std::string input;
std::string temp;
std::string temp2;
std::string temp3;
int counter = 0;
while (input != "e" && input != "r") {
std::cout << "Do you want to (r)ead the inventory or (e)dit it? (input 'r' or 'e'): ";
getline(std::cin, input);
}
if (input == "r") {
std::ifstream pFile ("products.txt");
if (pFile.is_open()) {
while (getline(pFile, line)) {
std::istringstream iss(line);
iss >> temp >> temp2 >> temp3;
counter++;
}
}
}
return 0;
}
Looking at the text file that you are using as an example and trying to populate a set of classes with the information I'd do something like this:
Text File
42 68 Apples
35 1 Oranges
70 25 Bananas
Looking at the text file you have an int followed by space then another int followed by another space finally followed by a varying size of char[]. We can use this information to create your class or struct and this is how I would create the class based off of the content from the file that is being read in or parsed.
Produce.h
#ifndef PRODUCE_H
#define PRODUCE_H
#include <string>
class Produce {
private:
unsigned price_; // Normally would use float but will use unsigned for simplicity
unsigned quantity_;
std::string name_; // You could use the int as an id as you were using
public:
Produce() {} // Default Constructor
~Produce() {} // Default Destructor
// User Constructor
Produce(const std::string& name, const unsigned& price, const unsigned& qty )
: name_(name), price_(price), quantity_( qty ) {}
// Copy By Const Reference Constructor
Produce(const Produce& other) {
name_ = other.name_;
price_ = other.price_;
quantity_ = other.quantity_;
}
// Assignment Operator
Produce& operator=(const Produce& other) {
name_ = other.name_;
price_ = other.price_;
quantity_ = other.quantity_;
return *this;
}
// Setters & Getters
void setOrChangePrice(const unsigned& priceChange) {
price_ = priceChange;
}
unsigned getPrice() const { return price_; }
void setName(const std::string& name) {
// Already Has A Name? Return!
if (!name_.empty())
return;
}
std::string getName() const { return name_; }
void setOrChangeQuantity(const unsigned& qty) {
quantity_ = qty;
}
unsigned getQuantity() const {
return quantity_;
}
};
#endif // PRODUCE_H
Produce.cpp
#include "Produce.h"
// Normally Constructor(s) & Function Definitions Would Go Here
// Since this is a simple class; I declared & defined them in the header.
Inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <vector>
#include "Produce.h"
class Inventory {
private:
std::vector<Produce> produce_;
public:
Inventory() {}
~Inventory() {
if (!produce_.empty()) {
produce_.clear();
}
}
std::vector<Produce> getProduceList() const {
return produce_;
}
unsigned getProduceListSize() const {
return static_cast<unsigned>( produce_.size() );
}
void addProduce(const Produce& produce) {
produce_.push_back(produce);
}
Produce getProduce(const std::string& name) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n];
} else {
return Produce();
}
}
}
unsigned getPrice(const std::string& name) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n].getPrice();
} else {
return 0;
}
}
}
unsigned getQuantity( const std::string& name ) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n].getQuantity();
} else {
return 0;
}
}
}
};
#endif // INVENTORY_H
Inventory.cpp
#include "Inventory.h"
Main.cpp
// #include <vector> // Also Included In Inventory.h
// #include <string> // Also Included In Produce.h
#include <iostream>
#include <fstream>
// #include "Produce.h" // Also Included In Inventory.h
#include "Inventory.h"
int main( ) {
// Same As Your Text File
std::string strFilename("ProduceInventory.txt");
std::ifstream fileIn;
// Temps
unsigned price = 0;
unsigned qty = 0;
std::string name;
Inventory inventory;
fileIn.open(strFilename.c_str());
if (!fileIn.is_open()) {
std::cout << "Can not read file\n";
}
while (fileIn >> price >> qty >> name) {
Produce produce(name, price, qty);
inventory.addProduce(produce);
}
if ( fileIn.is_open() ) {
fileIn.close();
}
// Test Our Inventory From File
for (unsigned n = 0; n < inventory.getProduceListSize(); n++) {
std::cout << "Name: " << inventory.getProduceList()[n].getName() << " "
<< "Price: " << inventory.getProduceList()[n].getPrice() << " "
<< "Qty: " << inventory.getProduceList()[n].getQuantity() << "\n";
}
std::cout << std::endl;
// Check To See If Our Search Method Works
std::cout << "Enter a product type by name to get its price and qty on hand.\n";
name.clear(); // reuse
std::cin >> name;
Produce p = inventory.getProduce(name);
if (p.getName().empty()) {
std::cout << "We either do not carry this produce or we are out of stock\n";
} else {
std::cout << "Our price is " << p.getPrice() << " and we have " << p.getQuantity() << " on hand\n";
// Or
std::cout << "Our price is " << inventory.getPrice(name) << " and we have " << inventory.getQuantity(name) << " on hand\n";
}
return 0;
}
Now this is just one of many ways this can be done; but also make sure that your text file is in the appropriate location of the working directory for your IDE or that you specify the correct path along with the filename and extension to be able to open and read from the file in the first place.
Much of this code can be fined even more; but I was showing how to use the std::vector<T> container and some of its functions and how to iterate through them and to retrieve its data. This is a basic way of parsing a simple text file when you know the exact format of the text file and for each and every line you will have the same data types in the same order.
This will not work for every kind of file parsing because it depends on the file's format. For example another file might have different kind of data from one line to the next and might have keywords or tags to give a description of what kind of data is coming next. For that kind of parsing you would have to read the entire line in first into a string stream then you would have to be able to parse that string stream via tokens to extract the data. Some times parsing a file might have multiple lines that belong to a data set and for that you would have to parse by chunks or blobs.
Parsing text files is harder to parse than binary file formats because you have to check each line and character of the text and you also have to be cautious
of character returns, new line characters etc. With binary format you just have to know how many bytes to read in and what type of data it is expected to be. There are many books that are written on just this topic alone on how to parse data from a file. There is no one simple way that fits all.

Iterate over array of objects from txt file

I have file with records separated by comas:
cities.txt:
1,NYC
2,ABQ
...
I would like to iterate over each row: ids and names. I have created the code:
#include <iostream>
#include <string>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, int name)
{
this->id = id;
this->name = name;
}
void load_file()
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
while (!v_file.eof()) {
//...
}
}
v_file.close();
}
}
int main()
{
City array_city[1000];
array_city.load_file();
return 0;
}
Could you tell me how to load all rows to array array_city and iterate over it? I don't know what to place in while block in load_file method. I don't know weather, the method load_file should have void type. Unfortunately I have to do it on arrays.
It's not a good idea to use EOF in a while loop. Read more in Why is iostream::eof inside a loop condition considered wrong?
In c++, vectors should be preferred over arrays. However, your teacher knows something more to suggest using an array here. For that reason I am providing a solution with an array:
Read the file line by line
Extract the id and the string
Assign it to the i-th cell of the array
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(City* cities, const int n)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number, i = 0;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities[i++] = {number, str};
}
}
v_file.close();
}
int main()
{
City cities[4]; // assuming there are 4 cities in the file
load_file(cities, 4);
for(unsigned int i = 0; i < 4; ++i)
cities[i].print();
return 0;
}
Same solution with std::vector, if you are interested. =) If you haven't been taught about them, I suggest you skip that part and come back later when you do that in the course.
Use a vector of City. Read the file line by line, and push back into the vector every line you read, by constructing an instance of your class, and you are done!
Example:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(vector<City>& cities)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities.push_back({number, str});
}
}
v_file.close();
}
int main()
{
vector<City> cities;
load_file(cities);
for(unsigned int i = 0; i < cities.size(); ++i)
cities[i].print();
return 0;
}
Input:
Georgioss-MacBook-Pro:~ gsamaras$ cat cities.txt
1,NYC
2,ABQ
3,CCC
4,DDD
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
ID = 1, name = NYC
ID = 2, name = ABQ
ID = 3, name = CCC
ID = 4, name = DDD

Issue with C++ using getline and vector

I have an issue where I am reading a line from a file using getline and the using a stringstream to separate the different variables using a comma as a delimiter. The issue is that a standard cout of the variables shows the seatDes properly, but using the vector I get the name back instead of the seatDes. Not sure why this is happening.
A standard line in file: Jane Doe,04202013,602,1A
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
#include "reservation.h"
int main(int argc, char **argv)
{
std::ifstream flightFile;
std::string name, date, seatDes, flightNum, line;
int error = 0, conFlightNum;
flightFile.open("reservations.txt");
if(!flightFile)
{
//returns a error value if there is a problem reading the file
error = 1;
return error;
}
else
{
//Start reading files and sticks them into a class object and sticks the object into the vector set
while (std::getline(flightFile, line))
{
std::istringstream ss(line);
std::getline(ss, name, ',');
std::getline(ss, date, ',');
std::getline(ss, flightNum, ',');
conFlightNum = atoi(flightNum.c_str());
ss >> seatDes;
reservation newRes(name, date, conFlightNum, seatDes);
std::cout << name << std::endl << date << std::endl << conFlightNum << std::endl << seatDes << std::endl;
std::cout << "Vector Component" << std::endl;
std::cout //<< newRes.getName() << std::endl << newRes.getDate() << std::endl << newRes.getFlightNum()
<< std::endl << newRes.getSeatDesg() << std::endl;
}
}
flightFile.close();
return 0;
}
reservation.h file
class reservation {
private:
std::string name, seatDesg, date;
int flightNum;
public:
//Default Constructor
reservation(){}
//Big Constructor
reservation(std::string name, std::string date, int flightNum, std::string seatDesg)
{
this->name = name;
this->seatDesg = name;
this->date = date;
this->flightNum = flightNum;
}
//Setters
void setName(std::string name)
{ this->name = name; }
void setFlightNum(int flightNum)
{ this->flightNum = flightNum; }
void setSeatDesg(std::string seatDesg)
{ this->seatDesg = seatDesg; }
void setDate(std::string date)
{ this->date = date; }
//Getters
std::string getName()
{ return name; }
std::string getSeatDesg()
{ return seatDesg; }
std::string getDate()
{ return date; }
int getFlightNum()
{ return flightNum; }
};
reservation(std::string name, std::string date, int flightNum, std::string seatDesg)
{
this->name = name;
this->seatDesg = name; // Here is your problem
this->date = date;
this->flightNum = flightNum;
}
Should be
this->seatDesg = seatDesg;