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.
Related
I am using Code::Blocks to write this C++ program, but everytime I do a 3rd Insert on the Link List, and when I use the Display option to check my work, I get a strange error. I have encountered no build errors. Please help check and advise when you have the chance, thank you.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
typedef struct student
{
string name;
int quiz1, quiz2, quiz3;
struct student *nxt;
} STUDENT;
class studentsStruct
{
private:
STUDENT *S; //Header of the Student List
public:
void init();
void add(string n, int a, int b, int c);
void del(string n);
void update(string n);
void save();
void retrieve();
void display();
};
int menu();
int updatemenu();
float round2(float x); // function to round the average and limit to 2 decimal points
int main()
{
studentsStruct ars;
string nm;
int a, b, c;
ars.init(); // Initialize the S Header of the Student List
ars.retrieve(); // Check if the "studentsdb.txt" is available and load the data as needed
while (1)
{
switch (menu())
{
case 1:
system("cls");
cout << "Insert Mode" << endl;
cout << "Name: ";
cin >> nm;
cout << "Input Quiz 1: ";
cin >> a;
cout << "Input Quiz 2: ";
cin >> b;
cout << "Input Quiz 3: ";
cin >> c;
ars.add(nm, a, b, c);
break;
case 2:
system("cls");
cout << "Update Mode" << endl;
cout << "Input Students Name: ";
cin >> nm;
ars.update(nm);
break;
case 3:
system("cls");
cout << "Delete Mode" << endl;
cout << "Enter Name: ";
cin >> nm;
ars.del(nm);
break;
case 4:
ars.display();
break;
case 5:
ars.save();
exit(0);
default:
cout << "1 to 5 only. ";
system("pause");
}
}
return 0;
}
void studentsStruct::init()
{
S = NULL;
}
void studentsStruct::add(string n, int a, int b, int c)
{
STUDENT *p, *q, *temp;
p = q = S;
temp = new STUDENT;
temp->name = n;
temp->quiz1 = a;
temp->quiz2 = b;
temp->quiz3 = c;
while (p != NULL)
{
q = p;
p = p->nxt;
}
if (p == S)
{
S = temp;
}
else
{
q->nxt = temp;
temp->nxt = p;
}
}
void studentsStruct::del(string n)
{
STUDENT *p, *q;
p = q = S;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << n << (" is not found.") << endl;
system("pause");
}
else
{
if (p == S)
{
S = S->nxt;
}
else
{
q->nxt = p->nxt;
delete (p);
cout << n << (" is deleted from the student records") << endl;
}
}
}
void studentsStruct::update(string n)
{
STUDENT *p, *q;
p = q = S;
int ua, ub, uc;
while (p != NULL && p->name != n)
{
q = p;
p = p->nxt;
}
if (p == NULL)
{
cout << ("Not Found") << endl;
system("pause");
}
else
{
while (1)
{
cout << "Update Mode" << endl;
cout << "Student : " << p->name << endl;
cout << "Quiz 1 Grade: " << p->quiz1 << endl;
cout << "Quiz 2 Grade: " << p->quiz2 << endl;
cout << "Quiz 3 Grade: " << p->quiz3 << endl;
switch (updatemenu())
{
case 1:
cout << "Quiz 1 Grade: ";
cin >> ua;
p->quiz1 = ua;
save();
break;
case 2:
cout << "Quiz 2 Grade: ";
cin >> ub;
p->quiz2 = ub;
save();
break;
case 3:
cout << "Quiz 3 Grade: ";
cin >> uc;
p->quiz3 = uc;
save();
break;
case 4:
main();
save();
break;
default:
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: " << endl;
}
}
}
}
int updatemenu()
{
int um;
cout << "Update Menu" << endl;
cout << "1.) Update Quiz 1 Grade" << endl;
cout << "2.) Update Quiz 2 Grade" << endl;
cout << "3.) Update Quiz 3 Grade" << endl;
cout << "4.) Return to the Main Menu" << endl;
cout << "Select an option between 1 to 3" << endl;
cout << "or select 4 to exit the Update Menu: ";
cin >> um;
return (um);
}
void studentsStruct::display()
{
STUDENT *p;
int i = 1;
p = S;
float ave;
string remarks;
system("cls");
cout << "No.\tName\tQuiz 1\tQuiz 2\tQuiz 3\tAverage\tRemarks\n";
while (p != NULL)
{
ave = (p->quiz1 + p->quiz2 + p->quiz3) / 3.0;
remarks = ave >= 75 ? "Passed" : "Failed";
cout << i++ << ".)\t" << p->name << "\t" << p->quiz1 << "\t" << p->quiz2 << "\t" << p->quiz3 << "\t" << round2(ave) << "\t" << remarks << endl;
p = p->nxt;
}
system("pause");
}
int menu()
{
int op;
cout << "Menu" << endl;
cout << "1.) Insert" << endl;
cout << "2.) Update" << endl;
cout << "3.) Delete" << endl;
cout << "4.) Display" << endl;
cout << "5.) Exit" << endl;
cout << "Select(1-5): ";
cin >> op;
return (op);
}
// Save the student data to "studentdb.txt" if available and create a file if needed
void studentsStruct::save()
{
STUDENT *p;
p = S;
ofstream stuData;
stuData.open("studentdb.txt");
while (p != NULL)
{
stuData << p->name << " " << p->quiz1 << " " << p->quiz2 << " " << p->quiz3 << endl;
p = p->nxt;
}
stuData.close();
}
// Check if the "studentdb.txt" is available and load the data as needed
void studentsStruct::retrieve()
{
ifstream fp;
string n;
int ax, by, cz;
fp.open("studentdb.txt");
if (fp.peek() != std::ifstream::traits_type::eof())
{
while (fp >> n >> ax >> by >> cz)
{
add(n, ax, by, cz);
}
}
else
{
cout << "The file is available but contains no records" << endl;
}
fp.close();
}
// function to round the average and limit to 2 decimal points
float round2(float x)
{
return trunc(x * 100.0) / 100.0;
}
And this is the error I am encountering (see screenshot below):
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.
I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});
Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.