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);
Related
For one of my options, I had to add a row of data to my struct array, I was able to update the array but it does not update the actual array. So I am trying to update my struct array by passing it as a reference. I placed the '&' sign before the name of the variable, but all my indexes within the function errored.. I'm still a newbie to programing and I'm not "allowed " to use any vectors according to my Professor. . I looked online and placed the '&' on the function name as well as on the prototype. I also changed it from void to the "data type" to return the updated array, but no luck... I hope this comes out clear....
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void readFile( ifstream& , string, Data [],int&);
void getEmployeeDetail(Data [], int&);
void getEmployeeLast(Data [], int&);
Data getAddEmployee(Data &, int&);
void getRemoveEmployee();
void getManagerOnly();
void getStaffOnly();
const int SIZE = 15;
Data employee[SIZE];
int main() {
ifstream inputFile;
ofstream outputFile;
int count = 0;
int selection;
const int EMPLOYEE_DETAIL = 1,
EMPLOYEE_LAST = 2,
ADD_EMPLOYEE = 3,
REMOVE_EMPLOYEE = 4,
MANAGER_ONLY = 5,
STAFF_ONLY = 6,
QUIT = 7;
readFile( inputFile ,"employeeData.txt", employee,count);
do {
cout << "\t Please select your option.\n"
<< "1. List all employee details\n"
<< "2. List employee by last name\n"
<< "3. Add a new employee\n"
<< "4. Remove an employee\n"
<< "5. Show all managers only\n"
<< "6. Show all staff only\n"
<< "7. Quit\n"
<< "Please enter your selection.\n" << endl;
cin >> selection;
while (selection < EMPLOYEE_DETAIL || selection > QUIT) {
cout << " Pleasse enter a valid selection.\n";
cin >> selection;
}
switch (selection) {
case EMPLOYEE_DETAIL:
getEmployeeDetail(employee,count);
break;
case EMPLOYEE_LAST:
getEmployeeLast(employee, count);
break;
case ADD_EMPLOYEE:
getAddEmployee(employee, count);
break;
case REMOVE_EMPLOYEE:
getRemoveEmployee();
break;
case MANAGER_ONLY:
getManagerOnly();
break;
case STAFF_ONLY:
getStaffOnly();
break;
case QUIT:
cout << "Program ending\n";
break;
}
} while (selection != QUIT);
system("pause");
return(0);
}
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void readFile(ifstream& inputFile, string data, Data employee[],int &count) {
inputFile.open(data);
if (!inputFile) {
cout << " Error in opening file\n";
exit(1);
}
else {
while (!inputFile.eof()) {
inputFile >> employee[count].first_name;
inputFile >> employee[count].last_name >> employee[count].employee_id >> employee[count].phone_number;
count++;
}
inputFile.close();
}
return;
};
void getEmployeeDetail( Data employee[], int& count) {
cout << "Firt Name" << "\t" << "Last Name " << "\t" << "Employee ID " << "\t" << "Phone Number \n";
cout << "--------------------------------------------------------------------------\n";
for(int i =0; i < count; i++)
cout <<employee[i].first_name<<"\t\t"<<employee[i].last_name<<"\t\t"<<employee[i].employee_id<<"\t\t"<<employee[i].phone_number<< "\n ";
cout << endl;
}
void getEmployeeLast(Data employee[], int& count) {
string searchName;
cout << "Please enter the last name of the employee you want to search for.\n";
cin >> searchName;
/*
for (int i = 0; i < count; i++)
if (searchName ==employee[i].last_name) {
cout << employee[i].last_name;
}
*/
string matchString = searchName;
for (int i = 0; i < count; i++) {
if (employee[i].last_name.find(matchString, 0) != std::string::npos) {
cout << employee[i].last_name << endl;
}
else {
cout << "No employee was located with that name.\n";
exit(1);
}
}
}
Data getAddEmployee(Data &employee, int& count) {
string firstName, lastName, phoneNumber;
int employeeID, size;
for (int i = 0; i < count; i++)
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
cout << count <<"\n";
size = count + 1;
cout << size << "\n";
cout << "Please enter the new employee First Name.\n";
cin >> firstName;
cout << "Please enter the new employee Last Name.\n";
cin >> lastName;
cout << "Please enter the new employee's ID.\n";
cin >> employeeID;
cout << "Please enter the new employee Phone Number.\n";
cin >> phoneNumber;
employee[10].first_name = firstName;
employee[10].last_name = lastName;
employee[10].employee_id = employeeID;
employee[10].phone_number = phoneNumber;
for (int i = 0; i < size; i++) {
cout << employee[i].first_name << "\t\t\t" << employee[i].last_name << "\t\t" << employee[i].employee_id << "\t\t" << employee[i].phone_number << "\n ";
cout << endl;
}
return employee;
}
First of all, your naming could be better. Like employeeList instead employee to specify its a list/array of employee, also addEmployee instead of getAddEmployee.
Second, instead of pasting whole code, it's better to paste the relevant block of code based on your question to make it clearer.
The solution is, your array is basically already on global scope, you don't need to pass it. Can just directly modify the array.
struct Data {
string first_name;
string last_name;
int employee_id;
string phone_number;
};
void addEmployee();
const int SIZE = 15;
Data employeeList[SIZE];
int current = 0;
int main(){
Data emp1 = {"John", "Doe", 100, "12345"};
employeeList[0] = emp1;
current++;
addEmployee();
for(int i=0; i<current; i++){
Data emp = employeeList[i];
cout<<i+1<<" "<<emp.first_name<<" "<<emp.phone_number<<endl;
}
}
void addEmployee(){
Data emp2 = {"Sam", "Smith", 200, "67890"};
employeeList[current] = emp2;
current++;
}
Can try it here: https://onlinegdb.com/drhzEOpis
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 was wondering if someone could help me on figuring out how to create multiple structs and also counting the number of structs created.
My Code follows three blocks, header file, Television file and then the main file.
Television.h
#include <iostream>
#include <string>
using namespace std;
class Televison {
string Manufacturer;
string Type; //Plasma, LCD
string Model; //Smart, regular
string Connection; //HDMI, VGA
string Power;
double Price;
int Serial_Number;
int Screen_size;
int Resolution; //larger one, so 1920 and etc.
int Channel; //any number
int Volume; //0 - 100
public:
//constructor
Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume);
//Destructor
~Televison();
//Accessor Methods
string get_Manufacturer();
string get_Type();
string get_Model();
string get_Connection();
string get_Power();
double get_Price();
int get_Serial_Number();
int get_Screen_size();
int get_Resolution();
int get_Channel();
int get_Volume();
//mutator methods
string input_Manufacturer(string Manufacturer);
string input_Type(string Type);
string input_Model(string Model);
string input_Connection(string Connection);
string input_Power(string Power);
double input_Price(double Price);
int input_Serial_Number(int Serial_Number);
int input_Screen_size(int Screen_size);
int input_Resolution(int Resolution);
int input_Channel(int Channel);
int input_Volume(int Volume);
string change_Power(string Power);
int change_Channel(int Channel);
int change_Volume(int Volume);
};
static int num_tel = 1; //number of Televisons that will be incremented
Television.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
//constructor
Televison::Televison(string Manufacturer, string Type, string Model, string Connection, string Power, double Price, int Serial_number, int Screen_size, int Resolution, int Channel, int Volume) {
this->Manufacturer = Manufacturer;
this->Type = Type;
this->Model = Model;
this->Connection = Connection;
this->Power = Power;
this->Price = Price;
this->Serial_Number = Serial_Number;
this->Screen_size = Screen_size;
this->Resolution = Resolution;
this->Channel = Channel;
this->Volume = Volume;
num_tel++;
// initiliazes the variables to default values
Manufacturer = "Sony";
Type = "Smart";
Model = "Plasma";
Connection = "HDMI";
Power = "ON";
Serial_Number = 1234;
Price = 199.00;
Screen_size = 50;
Resolution = 1440;
Channel = 100;
Volume = 100;
}
//Destructor
Televison::~Televison() {
cout << "The " << Manufacturer << " " << Model << " has finished shutting down." << endl;
num_tel--;
cout << "The inventory of television is now: " << num_tel << endl;
}
//Get Methods
string Televison::get_Manufacturer() {
return Manufacturer;
}
string Televison::get_Model() {
return Model;
}
string Televison::get_Type() {
return Type;
}
int Televison::get_Serial_Number() {
return Serial_Number;
}
string Televison::get_Connection() {
return Connection;
}
string Televison::get_Power() {
return Power;
}
double Televison::get_Price() {
return Price;
}
int Televison::get_Screen_size() {
return Screen_size;
}
int Televison::get_Resolution() {
return Resolution;
}
int Televison::get_Channel() {
return Channel;
}
int Televison::get_Volume() {
return Volume;
}
//mutator methods
int Televison::change_Channel(int Channel1) {
if (Channel > 0)
{
Channel = Channel1;
return Channel;
}
else
{
cout << "Invalid Channel, please enter another number" << endl;
return Channel;
}
}
int Televison::change_Volume(int Volume1) {
if (Volume1 > 0)
{
Volume = Volume1;
return Volume;
}
else
{
cout << "Invalid volume, please enter another number" << endl;
return Volume;
}
}
string Televison::change_Power(string Power1) {
if (Power1 =="Y")
{
Power = Power1;
return Power;
}
else
{
return Power;
}
}
string Televison::input_Connection(string Connection1) {
Connection = Connection1;
return Connection;
}
string Televison::input_Type(string M) {
Type = M;
return Type;
}
string Televison::input_Manufacturer(string M) {
Manufacturer = M;
return Manufacturer;
}
/*
string Televison::Manufacturer_code(string M,string N) {
string J = M.substr(0,4);
string Manufacturer_code = J + N;
return Manufacturer_code;
}
*/
string Televison::input_Model(string M) {
Model = M;
return Model;
}
string Televison::input_Power(string M) {
Power = M;
return Power;
}
double Televison::input_Price(double M) {
Price = M;
return Price;
}
int Televison::input_Serial_Number(int M) {
Serial_Number = M;
return Serial_Number;
}
int Televison::input_Screen_size(int M) {
Screen_size = M;
return Screen_size;
}
int Televison::input_Resolution(int M) {
Resolution = M;
return Resolution;
}
int Televison::input_Channel(int M) {
Channel = M;
return Channel;
}
int Televison::input_Volume(int M) {
Volume = M;
return Volume;
}
Source.cpp
#include <iostream>
#include <string>
#include "Televison.h"
using namespace std;
void displayStatus(Televison& Televison) {
cout << "Inventory of Televisons: " << num_tel << endl;
cout << "The Televison serial number: " << Televison.get_Serial_Number() << " " << Televison.get_Manufacturer() << " " << Televison.get_Model() << " " << Televison.get_Type() << " with " << Televison.get_Connection() << " ";
cout << "\n with " << Televison.get_Power() << " " << Televison.get_Price() << " with " << Televison.get_Screen_size() << " screen size " << Televison.get_Resolution() << "p " << "with " << Televison.get_Channel() << " channel " << Televison.get_Volume() << " Volume " << endl;
}
int main() {
{
Televison Televison_1("Sony", "Smart", "Plasma", "HDMI", "ON", 199.00, 1234, 50, 1440, 100, 100); //default Televison
cout << "This is the Televison program for personal Televison: " << endl;
bool repeat = true;
do {
cout << "Please enter the Manufacturer for the Televison: " << endl;
string Manufacturer;
getline(cin, Manufacturer);
int M1 = Manufacturer.length();
if (M1 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Manufacturer(Manufacturer);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Type of the Televison: " << endl;
string Type;
getline(cin, Type);
int M3 = Type.length();
if (M3 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Type(Type);
} while (!repeat);
repeat = true;
do {
cout << "Please enter the Model for the Televison: " << endl;
string Model;
getline(cin, Model);
int M2 = Model.length();
if (M2 < 1)
{
cout << "No input, please try again" << endl;
repeat = false;
}
else
repeat = true;
Televison_1.input_Model(Model);
} while (!repeat);
cout << "Please enter the Connection for the Televison: " << endl;
string Connection;
cin >> Connection;
Televison_1.input_Connection(Connection);
cout << "Enter the Serial Number: " << endl;
int inp4;
cin >> inp4;
Televison_1.input_Serial_Number(inp4);
cout << "Enter the Screen size: " << endl;
cin >> inp4;
Televison_1.input_Screen_size(inp4);
cout << "Enter the Resolution: " << endl;
cin >> inp4;
Televison_1.input_Resolution(inp4);
int a = 0;
while (a < 1)
{
cout << "Please enter the Price for the Televison: " << endl;
double Price;
cin >> Price;
if (Price > 0) //address speed must be greater than 0
{
Televison_1.input_Price(Price);
a++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int b = 0;
while (b < 1)
{
cout << "Would you like to Power your Televison? (Y/N)" << endl;
char input1;
cin >> input1;
if (input1 == 'Y' || input1 == 'y')
{
Televison_1.change_Power("ON");
b++;
}
else if (input1 == 'N' || input1 == 'n')
{
Televison_1.change_Power("OFF");
b++;
}
else
cout << "Invalid, enter again." << endl;
}
displayStatus(Televison_1);
int n = 0;
int n1 = 0;
while (n < 1)
{
cout << "Would you like to change any of the following attributes of your Televison? (Y/N)";
string input2, input3;
int input4;
double input5;
cin >> input2;
if (input2 == "Y" || input2 == "y")
{
while (n1 < 1) {
cout << "Which Televison attribute would you like to change? (Enter the respective number): " << endl;
cout << "1: Manufacturer" << endl;
cout << "2: Type" << endl;
cout << "3: Model" << endl;
cout << "4: Serial Number" << endl;
cout << "5: Connection" << endl;
cout << "6: Power" << endl;
cout << "7: Channel" << endl;
cout << "8: Screen size" << endl;
cout << "9: Resolution" << endl;
cout << "10: Volume" << endl;
cout << "11: Price" << endl;
int choice;
cin >> choice;
bool repeat1 = true;
bool repeat2 = true;
bool repeat3 = true;
switch (choice)
{
case 1:
cout << "Enter the Manufacturer: " << endl;
cin >> input3;
Televison_1.input_Manufacturer(input3);
break;
case 2:
cout << "Enter the Type: " << endl;
cin >> input3;
Televison_1.input_Type(input3);
break;
case 3:
cout << "Enter the Model: " << endl;
cin >> input3;
Televison_1.input_Model(input3);
break;
case 4:
cout << "Enter the Serial Number: " << endl;
cin >> input4;
Televison_1.input_Serial_Number(input4);
break;
case 5:
cout << "Enter the Connection: " << endl;
cin >> input3;
Televison_1.input_Connection(input3);
break;
case 6:
cout << "Enter the power: " << endl;
cin >> input3;
Televison_1.input_Power(input3);
break;
case 7:
cout << "Enter the Channel " << endl;
cin >> input4;
Televison_1.input_Channel(input4);
break;
case 8:
cout << "Enter the Screen size: " << endl;
cin >> input4;
Televison_1.input_Screen_size(input4);
break;
case 9:
do {
cout << "Enter the Resolution: " << endl;
cin >> input4;
if (input4 < 0)
{
cout << "Please enter a speed above 0" << endl;
repeat1 = false;
}
else
{
Televison_1.input_Resolution(input4);
repeat1 = true;
}
} while (!repeat1);
break;
case 10:
do {
cout << "Enter the Volume: " << endl;
cin >> input4;
if (input4 >= 0) {
cout << "Please enter a valid volume" << endl;
repeat2 = false;
}
else
{
repeat2 = true;
Televison_1.change_Volume(input4);
}
} while (!repeat2);
break;
case 11:
do {
cout << "Enter the Price: " << endl;
cin >> input5;
if (input5 > 0)
{
Televison_1.input_Price(input5);
repeat3 = true;
}
else
{
cout << "Please enter a valid price" << endl;
repeat3 = false;
}
} while (!repeat3);
break;
}
displayStatus(Televison_1);
cout << "Would you like to change another attribute? (Y/N)" << endl;
cin >> input3;
if (input3 == "Y" || input3 == "y")
{
}
else
n1++;
}
n++;
}
else if (input2 == "N" || input2 == "n")
{
cout << "The Televison will begin to shut down." << endl;
n++;
displayStatus(Televison_1);
}
else
cout << "Invalid, enter again." << endl;
}
}
// object goes out of scope - the destructor which shuts down the Televison
system("pause");
return 0;
}
Basically, my code only allows me to create one object and modify it. However, I would like to add the ability to create multiple objects and have a counter for it. I tried adding a counter, but it seems that doesn't work very well... I don't need someone to solve it, but if someone could point me to the right direction, that would be great.
Error 1 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 2 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\main.obj Project17
Error 3 error LNK2005: "class ticket tick" (?tick##3Vticket##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 4 error LNK2005: "class bus bs" (?bs##3Vbus##A) already defined in bus.obj c:\Users\tahir\documents\visual studio 2013\Projects\Project17\Project17\ticket.obj Project17
Error 5 error LNK1169: one or more multiply defined symbols found c:\users\tahir\documents\visual studio 2013\Projects\Project17\Debug\Project17.exe 1 1 Project17
bus.h
#pragma once
class bus
{
int busno;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *busname;
char *startpoint;
char *destination;
public:
bus();
void input();
int rbusno();
int rnoofkidsseats();
int rnoofwomenseats();
int rnoofmenseats();
int rnoofspecialseats();
int rnoofvvip();
void display();
}bs;
bus.cpp
#include <iostream>
#include <fstream>
#include "bus.h"
#include "ticket.h"
#include "windows.h"
using namespace std;
int length(char arr[])
{
int i = 0;
for (; arr[i] != '\0'; i++);
return i;
}
void gotoxy(int x, int y)
{
static HANDLE h = NULL;
if (!h)
h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD c = { x, y };
SetConsoleCursorPosition(h, c);
}
bus::bus()
{
busno = 0;
noofkidsseats = 0;
noofwomenseats = 0;
noofmenseats = 0;
noofspecialseats = 0;
noofvvip = 0;
busname = '\0';
startpoint = '\0';
destination = '\0';
}
int bus::rbusno()
{
return busno;
}
int bus::rnoofkidsseats()
{
return noofkidsseats;
}
int bus::rnoofwomenseats()
{
return noofwomenseats;
}
int bus::rnoofmenseats()
{
return noofmenseats;
}
int bus::rnoofspecialseats()
{
return noofspecialseats;
}
int bus::rnoofvvip()
{
return noofvvip;
}
void bus::input()
{
cout << "ENTER THE BUS NUMBER: ";
cin >> busno;
cout << "ENTER THE NUMBER OF SEATS FOR KIDS: ";
cin >> noofkidsseats;
cout << "ENTER THE NUMBER OF SEATS FOR WOMEN: ";
cin >> noofwomenseats;
cout << "ENTER THE NUMBER OF SEATS FOR MEN: ";
cin >> noofmenseats;
cout << "ENTER THE NUMBER OF SEATS SPECIAL PERSONS: ";
cin >> noofspecialseats;
cout << "ENTER THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cin >> noofvvip;
cout << "ENTER THE BUS NAME: ";
char name[20];
cin >> name;
int l = length(name);
busname = new char[l];
int i;
for (i = 0; i < l; i++)
busname[i] = name[i];
busname[i] = '\0';
cout << "ENTER THE STARTING POINT: ";
char start[20];
cin >> start;
int L = length(start);
startpoint = new char[L];
int j;
for (j = 0; j < L; j++)
startpoint[j] = start[j];
startpoint[j] = '\0';
cout << "ENTER THE DESTINATION: ";
char end[20];
cin >> end;
int s = length(end);
destination = new char[s];
int k;
for (k = 0; k < s; k++)
destination[k] = end[k];
destination[k] = '\0';
}
void bus::display()
{
cout << " ***************************************" << endl;
cout << " * *" << endl;
cout << " * BUS DEATAILS *" << endl;
cout << " * *" << endl;
cout << " ***************************************" << endl;
cout << " THE BUS NUMBER: ";
cout << busno << endl;
cout << " THE BUS NAME: ";
cout << busname << endl;
cout << " STARTING POINT: ";
cout << startpoint << endl;
cout << " DESTINATION: ";
cout << destination << endl;
cout << " THE NUMBER OF SEATS FOR KIDS: ";
cout << noofkidsseats << endl;
cout << " THE NUMBER OF SEATS FOR WOMEN: ";
cout << noofwomenseats << endl;
cout << " THE NUMBER OF SEATS FOR MEN: ";
cout << noofmenseats << endl;
cout << " THE NUMBER OF SEATS SPECIAL PERSONS: ";
cout << noofspecialseats << endl;
cout << " THE NUMBER OF SEATS FOR VVIP PASSENGERS: ";
cout << noofvvip << endl;
}
ticket.h
#pragma once
class ticket
{
int resno;
int age;
int tokids;
int towomen;
int tomen;
int tospecial;
int tovvip;
int noofkidsseats;
int noofwomenseats;
int noofmenseats;
int noofspecialseats;
int noofvvip;
char *pname;
char *status;
public:
ticket();
void reservation();
int returnresno();
void cancellation();
void print();
}tick;
ticket.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "ticket.h"
#include "bus.h"
using namespace std;
ticket::ticket()
{
resno = 0;
age = 0;
tokids = 0;
towomen = 0;
tomen = 0;
tospecial = 0;
tovvip = 0;
pname = '\0';
status = '\0';
}
int ticket::returnresno()
{
return resno;
}
void ticket::print()
{
int f = 0;
system("cls");
ifstream fn("Ticket1.dat", ios::out); fn.seekg(0);
if (!fn)
{
cout << "ERROR IN THE FILE ";
}
X:
cout << "ENTER THE RESERVATION NO ";
int n;
cin >> n;
while (!fn.eof())
{
fn.read((char*)&tick, sizeof(tick));
if (n == resno)
{
f = 1;
system("cls");
cout << "NAME: ";
cout << pname;
cout << "AGE: ";
cout << age;
cout << "PRESENT STATUS: ";
cout << status;
cout << "RESERVATION NUMBER: ";
cout << resno;
cout << "PRESS ANY KEY TO CONTINUE ";
system("pause");
}
}
if (f == 0)
{
system("cls");
cout << "UNRECOGINIZED RESERVATION NO !!! WANNA RETRY ? (Y / N) ";
char a;
cin >> a;
if (a == 'y' || a == 'Y')
{
system("cls");
goto X;
}
else
{
cout << "PRESS ANY KEY TO CONTINUE";
system("pause");
}
}
fn.close();
}
void ticket::reservation()
{
system("cls");
cout << "RESERVATION ";
cout << "ENTER THE BUS NO: ";
int bno, f = 0; cin >> bno; ofstream file;
ifstream fin("bus1.dat", ios::out); fin.seekg(0);
if (!fin)
{
system("cls");
cout << "ERROR IN THE FILE ";
system("cls");
while (!fin.eof())
{
fin.read((char*)&bs, sizeof(bs)); int z;
z = bs.rbusno();
if (bno == z)
{
f = 1;
noofkidsseats = bs.rnoofkidsseats();
noofwomenseats = bs.rnoofwomenseats();
noofmenseats = bs.rnoofmenseats();
noofspecialseats = bs.rnoofspecialseats();
noofvvip = bs.rnoofvvip();
}
}
if (f == 1)
{
file.open("Ticket1.dat", ios::app);
S:
system("cls");
cout << "NAME:";
cin >> pname;
cout << "AGE:";
cin >> age;
system("cls");
cout << "SELECT THE CATEGORY WHICH YOU WISH TO TRAVEL";
cout << "1.KIDS CATEGORY: ";
cout << "2.WOMEN CATEGORY: ";
cout << "3.MEN CATEGORY: ";
cout << "4.SPECIAL CATEGORY: ";
cout << "5.SECOND CLASS SLEEPER: ";
cout << "ENTER YOUR CHOICE ";
int c;
cin >> c;
switch (c)
{
case 1:
tokids++;
resno = rand();
if ((noofkidsseats - tokids)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 2:
towomen++;
resno = rand();
if ((noofwomenseats - towomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO:";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 3:
tomen++;
resno = rand();
if ((noofmenseats - tomen)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO: ";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 4:
tospecial++;
resno = rand();
if ((noofspecialseats - tospecial)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
case 5:
tovvip++;
resno = rand();
if ((noofvvip - tovvip)>0)
{
status = "confirmed";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
else
{
status = "pending";
cout << "STATUS";
puts(status);
cout << "RESERVATION NO";
cout << resno;
system("pause");
file.write((char*)&tick, sizeof(tick)); break;
}
}
cout << "DO YOU WISH TO CONTINUE BOOKING TICKETS (Y/N) ? ";
char n;
cin >> n;
if (n == 'y' || n == 'Y')
{
goto S;
}
}
}
if (f == 0)
{
system("cls");
cout << "ERROR IN THE BUS NUMBER ENTERED !!!";
system("pause");
}
file.close();
}
void ticket::cancellation()
{
system("cls");
ifstream fin;
fin.open("Ticket1.dat", ios::out);
ofstream file;
file.open("Temp1.dat", ios::app);
fin.seekg(0);
cout << "ENTER THE RESERVATION NO: ";
int r, f = 0;
cin >> r;
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
while (!fin.eof())
{
fin.read((char*)&tick, sizeof(tick)); int z;
z = returnresno();
if (z != r)
{
file.write((char*)&tick, sizeof(tick));
}
if (z == r)
{
f = 1;
}
}
file.close(); fin.close();
remove("Ticket1.dat");
rename("Temp1.dat", "Ticket1.dat");
if (f == 0)
{
cout << "NO SUCH RESERVATION IS MADE !!! PLEASE RETRY ";
system("pause");
}
else
{
cout << "RESERVATION CANCELLED";
system("pause");
}
}
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "bus.h"
#include "ticket.h"
using namespace std;
int main()
{
ticket obj;
bus obj1;
int ch, r = 1000, j;
cout << "WELCOME";
Z:
cout << "BUS TICKET RESERVATION";
cout << "==========================";
cout << "1.BUS DETAILS";
cout << "2.UPDATE BUS DETAILS ";
cout << "3.RESERVING A TICKET ";
cout << "4.CANCELLING A TICKET";
cout << "5.DISPLAY THE PRESENT TICKET STATUS ";
cout << "6.EXIT";
cout << "ENTER YOUR CHOICE: ";
cin >> ch;
char n;
switch (ch)
{
case 1:
{
ifstream fin("bus1.dat", ios::out);
fin.seekg(0);
if (!fin)
{
cout << "ERROR IN THE FILE !!!";
}
else
{
while (!fin.eof())
{
fin.read((char*)&obj1, sizeof(obj1));
bs.display();
}
}
fin.close();
goto Z;
}
case 2:
{
cout << "ENTER THE PASSWORD ";
cin >> j;
cout << "CHECKING PLEASE WAIT ";
system("pause");
Y:
ofstream fout("bus1.dat", ios::app);
bs.input();
fout.write((char*)&obj1, sizeof(obj1));
fout.close();
cout << "DO YOU WISH TO CONTINUE UPDATING ?(Y/N)";
cin >> n;
if (n == 'y' || n == 'Y')
{
goto Y;
goto Z;
}
else
{
goto Z;
}
}
case 3:
{
obj.reservation();
goto Z;
}
case 4:
{
obj.cancellation();
goto Z;
}
case 5:
{
obj.print();
goto Z;
}
case 6:
{
exit(0);
}
}
system("pause");
return 0;
}
class bus
{
// members
}bs;
Not only declares a type bus but also a defines a variable bs. The same for tick.
When you include these headers in several cpp files, you get several definitions of these variables.
I'm sure none of the C++ books you have read told you to define variables like this in header files, so just don't. Declare the types in the headers and the variables where you need them, likely in the cpp files.
Hello I am having issues with a final project. The objective is to have the user create a form that allows a user to view data, edit data, add data, and save their password data in an encoded format. The program starts with an input file made by the user. The delimiter is ';', and the first char is a "code", then the, site, username, password, and notes follow.
I am very new to vectors, and I am not allowed to use a 2d array, or map.
Thank you for your time.
#include <iomanip>
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
const int MAX_SIZE = 30;
const int BUFFER_SIZE = 200;
struct dataRow {
string site, user, pass, notes;
string code;
};
string inFileName; //name of inputfile
string outFileName;
ifstream pathStream;
ofstream outFile;
char inputChar;
int extPosition(1), count = 0,lineNum;
void displayVector(vector<dataRow> inputData);
void viewLineData(vector<dataRow> inputData, int lineNum);
void addNewRow(vector<dataRow> inputData,int& lastRowNum, string site, string user, string pass, string notes);
void editLineData(vector<dataRow> inputData, int& lineNum, string site, string user, string pass, string notes);
void warning();
void cleanBuffer();
bool displayMenu();
int exit();
dataRow descripLine;
int main()
{
vector<dataRow> inputData;
string rowDescripin,userin,passin,notesin,sitein;
string codein,errorMsg;
int lastRow;
//add a .txt extension to the file if the user didn't provide an extension
if (inFileName.size() > 4)
// If there's a valid extension, it will be in the last 4 positions of the string; Adjust by 1 for 0 offset
extPosition = inFileName.size() - 4;
int ext = inFileName.find_last_of(".txt");
if (!(inFileName.find_last_of(".") == extPosition))
{
inFileName += ".txt";
}
cout << "\nPlease enter the filename of input file: ";
cin >> inFileName;
pathStream.open(inFileName.c_str());
if (pathStream.fail())
{
cerr << inFileName << " failed to open.\n";
system("pause");
exit(1);
}
else
{
cout << "startup success" << endl;
}
getline(pathStream, codein, ';');
descripLine.code = codein;
while (!pathStream.eof())
{
getline(pathStream, sitein, ';');
descripLine.site = sitein;
getline(pathStream, userin, ';');
descripLine.user = userin;
getline(pathStream, passin, ';');
descripLine.pass = passin;
getline(pathStream, notesin, ';');
descripLine.notes = notesin;
inputData.push_back(descripLine);
}
displayVector(inputData);
displayMenu();
while (cin){
cin >> inputChar;
inputChar = toupper(inputChar);
//Adjust calculations based on inputCHar
if (inputChar == 'D') // Display line descriptions
{
displayVector(inputData);
}
else if (inputChar == 'V') //View line data
{
cout << "Enter line number you wish to view: ";
cin >> lineNum;
viewLineData(inputData, lineNum);
}
/* else if (inputChar == 'E') //Edit line Data
{
cout << "Enter line number you wish to edit: ";
cin >> lineNum;
editLineData(inputData, lineNum);
}*/
else if (inputChar == 'A') //Add line data
{
warning();
lastRow = inputData.size();
cout << "Enter a line description: ";
cin >> rowDescripin;
cout << "Enter a line username: ";
cin >> userin;
cout << "Enter a line password: ";
cin>>passin;
cout << "Enter notes: ";
cin>>notesin;
addNewRow(inputData, lastRow, rowDescripin, userin, passin, notesin);
}
/*else if (inputChar == 'S') //Save and encode file
{
}*/
else if (inputChar == 'X') //exit program
{
exit();
}
}
system("pause");
}
bool displayMenu()
{
cout << endl << " AVAILABLE OPTIONS " << endl << endl <<
"D - DISPLAY LINE DESCRIPTIONS" << endl <<
"V - VIEW LINE DATA" << endl <<
"E - EDIT LINE DATA" << endl <<
"A - ADD LINE DATA" << endl <<
"S - SAVE AND ENCODE FILE" << endl <<
"X - EXIT PROGRAM" << endl;
return 0;
}
void viewLineData(vector<dataRow> inputData,int lineNum)
{
cout << inputData[lineNum].site << endl << inputData[lineNum].user<<endl<<inputData[lineNum].pass <<endl<<inputData[lineNum].notes;
}
void displayVector(vector<dataRow> inputData)
{
cout << fixed << setprecision(3);
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << left << setw(20) << inputData[i].site ;
}
}
void addNewRow(vector<dataRow> inputData, int& lastRowNum, string site, string user, string pass, string notes)
{
char ans;
cout << "You have entered:" << endl << site << endl << user << endl << pass << endl << notes<<endl;
cout << "Is this the data you wish to add (Y/N)? ";
cin >> ans;
ans = toupper(ans);
if (ans == 'Y')
{
dataRow tempRow = { site, user, pass, notes };
inputData.push_back(tempRow);
cout << inputData.size();
int num = inputData.size()-1;
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << inputData[i].site << endl << inputData[i].user << endl << inputData[i].pass << endl << inputData[i].notes;
}
}
else if (ans == 'N')
{
cout << "ok enter of no";
}
}
void warning()
{
cout<< "WARNING: You cannot use semi-colons in these fields. Any semi-colons entered will be removed." << endl;
return;
}
int exit()
{
pathStream.close();
system("pause");
return 0;
}
void cleanBuffer()
{
cin.clear();
cin.ignore(BUFFER_SIZE, '\n');
}