Trying to make the string "Abbot" the [1] slot of my basePlayer array. Basically they select the player in the switch and then the player string will be stored in array.
line 118
Help would be SUPER appreciated, program will run if you copy, paste, compile, and run.
Thank you for taking a look!!
#include <iostream>
#include <string>
#include <windows.h>
#include <cmath>
#include <cstring>
#include <cstdlib>
using namespace std;
int main(){
Beep(251.63,100);
Beep(329.63,100);
Beep(392,100);
Beep(251.63,100);
Beep(329.63,100);
Beep(392,100);
Beep(251.63,100);
Beep(329.63,100);
Beep(392,100);
string playerList[6] = {"Abbot", "Seer", "Hellion", "Vagabond", "Knave","##QUIT##"};
string cityList[4] = {"city1","city2","city3","city4"};
string spiritList[4] = {"spirit1","spirit2","spirit3","spirit4",};
string yesNo[2] = {"yes","no"};
string name;
string player;
string city;
string spirit;
string basePlayer[4] = {name, player, city, spirit};
int pointer = 0;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 5);
cout << "What is your name?" << endl;
cin >> name;
cout << "your name is " << name << "?" << endl;
basePlayer[0] = name;
while(true){
system("cls");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 5);
cout << basePlayer[0]<<" please choose your Adventurer:\n*tab* for description\n\n";
for (int row = 0; row < 6; ++row){
if(row == pointer){
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
cout << playerList[row] << endl;}
else{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 5);
cout << playerList[row] << endl;}}
while(true){
if (GetAsyncKeyState(VK_UP) != 0){
Beep(800,50);
pointer -= 1;
if (pointer == -1){
pointer = 0;}
break;}
else if (GetAsyncKeyState(VK_DOWN) != 0){
Beep(800,50);
pointer += 1;
if (pointer == 6){
pointer = 0;}
break;}
else if (GetAsyncKeyState(VK_TAB) != 0){
Beep(1200,50);
Beep(1000,50);
switch(pointer){
case 0:{
system("cls");
cout << "AbbotFacts.\n\n*RightArrow* to become the Abbot\n*ArrowDown* to return to TitleScreen";
Sleep(1000);
}
break;
case 1:{
system("cls");
cout << "SeerFacts.\n\n*RightArrow* to become the Sear\n*ArrowDown* to return to TitleScreen";
Sleep(1000);
}
break;
case 2:{
system("cls");
cout << "HellionFacts.\n\n*RightArrow* to become the Hellion\n*ArrowDown* to return to TitleScreen";
Sleep(1000);
}
break;
case 3:{
system("cls");
cout << "VagabondFacts.\n\n*RightArrow* to become the Vagabond\n*ArrowDown* to return to TitleScreen";
Sleep(1000);
}
break;
case 4:{
system("cls");
cout << "KnaveFacts.\n\n*RightArrow* to become the Knave\n*ArrowDown* to return to TitleScreen";
Sleep(1000);
}
break;
case 5:{return 0;}
break;
break;}}
else if (GetAsyncKeyState(VK_RIGHT) != 0){
Beep(1000,50);
Beep(1200,50);
switch(pointer){
case 0:{
system("cls");
player = "Abbot";
cout << basePlayer[0] << ", You have chosen the "<< basePlayer[1] << endl;
Sleep(1000);
}
break;
case 1:{
system("cls");
cout << "You have chosen the Seer"<< endl;
player="Seer";
cout << basePlayer[1] << endl;
Sleep(1000);
}
break;
case 2:{
system("cls");
cout << "You have chosen the Hellion"<< endl;
player="Hellion";
cout << basePlayer[1] << endl;
Sleep(1000);
}
break;
case 3:{
system("cls");
cout << "You have chosen the Vagabond" << endl;
player="Vagabond";
cout << basePlayer[1] << endl;
Sleep(1000);
}
break;
case 4:{
system("cls");
cout << "You have chosen the Knave"<< endl;
player="Knave";
cout << basePlayer[1] << endl;
Sleep(1000);
}
break;
case 5:{return 0;
break;}
break;}}
}
Sleep(150);
}
}
What you have to do is assign player to basePlayer[1] after setting the player value.
switch(pointer){
case 0:{
player = "Abbot";
basePlayer[1] = player;
cout << "You have chosen the "<< basePlayer[1] << endl;
I advise you have a read up on how character arrays work in C++, and memory allocation.
If you want a simpler solution, you might like the std string library, which handles most of the memory and copying side for you.
I seriously think you might want to try something simpler first, or at least look in to an oop design, which might be simpler in this case.
It would be much, much better to store this data in a structure rather than an array. This would allow you to group other player data that may not be represented as a string.
struct PlayerData
{
std::string m_Name;
std::string m_Player;
std::string m_City;
std::string m_Spirit;
int m_MaxHealth;
};
...
PlayerData basePlayer;
basePlayer.m_Name = playerList[playerSelection];
Better yet why not have a class store this data, allowing you to control access to it and also perform operations with the data.
class Player
{
public:
Player( const std::string& name, const std::string& player, const std::string& city, const std::string& spirit );
virtual ~Player();
std::string GetName() const;
void ReduceHealth( int damage );
private:
std::string m_Name;
std::string m_Player;
std::string m_City;
std::string m_Spirit;
int m_MaxHealth;
};
You may want to read up more on C++ itself and it's features before attempting a to write a whole game.
Related
This program is essentially supposed to count the results of random throws of a dice 100 times and count the occurrence of each face then display all of them as a histogram of asterisks. It would seem the functions could be working but i'm unable to verify because after I make my choice, nothing displays.
#include <iostream>
#include <iomanip>
#include <string>
#include <random>
#include <sstream>
using namespace std;
enum class Side {
ONE, TWO, THREE, FOUR, FIVE, SIX
};
struct Bar {
int value;
Side label;
};
//roll dice function
void rollDice( Bar h[], int n = 100);
void rollDice( Bar h[], int){
default_random_engine en;
uniform_int_distribution<> dist{1,6};
int results[] ={0,0};
for( int n; n<=100; n++){
cout << dist(en);
results[dist(en)]++;
h[n].value = results[n];
if(h[n].value == 1){
h[n].label = Side::ONE;
}
else if(h[n].value == 2){
h[n].label = Side::TWO;
}
else if(h[n].value == 3){
h[n].label = Side::THREE;
}
else if(h[n].value == 4){
h[n].label = Side::FOUR;
}
else if(h[n].value == 5){
h[n].label = Side::FIVE;
}
else {
h[n].label = Side::SIX;
}
}
};
string getHistogram(Bar h[], char c = '*');
string getHistogram(Bar h[], char c ){
stringstream ast;
for( int n; n<=100; n++){
switch (h[n].label)
{
case Side::ONE:
return to_string(c);
break;
case Side::TWO:
return to_string(c);
break;
case Side::THREE:
return to_string(c);
break;
case Side::FOUR:
return to_string(c);
break;
case Side::FIVE:
return to_string(c);
break;
case Side::SIX:
return to_string(c);
break;
default:
break;
}
}
ast << "One: " << c << endl;
ast << "Two: " << c << endl;
ast << "Three: " << c << endl;
ast << "Four: " << c << endl;
ast << "Five: " << c << endl;
ast << "Six: " << c << endl;
string output = ast.str();
cout<< output;
return output;
}
int main (){
Bar histogram[] = {
{0,Side::ONE},{0,Side::TWO}, {0,Side::THREE},
{0,Side::FOUR},{0,Side::FIVE}, {0,Side::SIX}
};
char choice;
do {
cout << "DICE ROLLING SIMULATION" << endl
<<"===============================" << endl
<< "r. Roll Dice" << endl
<< "h. Display histogram" << endl
<< "q. Quit program\n" << endl
<< "\nEnter your choice:" << endl;
// Reading a single character using the scanner
cin >> choice;
switch(choice) {
case 'r': case 'R':
rollDice(histogram, 100);
break;
case 'h': case 'H':
cout<< getHistogram(histogram, '*');
break;
case 'q': case 'Q':
cout << "Good bye\n" << endl;
break;
default:
cout << "Invalid choice\n" << endl;
}
} while(choice != 'q');
}
So, this code contains many different mistakes. Let's go in order.
In structBar label may be const
struct Bar {
int value;
const Side label;
};
You don't need forward declaration for function signature
In rollDice you have many unnecessary local variables and I would use mt19937 random generator. So rollDice will look like this
void rollDice(Bar h[], int count = 100) {
default_random_engine en;
uniform_int_distribution<> dist{1,6};
for( int n = 0; n <= count; n++) {
cout << dist(en) << endl;
const auto index = dist(en) - 1;
++h[index].value;
}
};
In getHistogram you have return to_string(c); in switch therefore you don't see histogram. You can delete swith because you can match index and Side. And why cycle up to 100?
string getHistogram(Bar h[], char c = '*') {
stringstream ast;
for( int n = 0; n <= 5; n++) {
const string strValue = string(h[n].value, c);
switch (h[n].label)
{
case Side::ONE: ast << "One: "; break;
case Side::TWO: ast << "Two: "; break;
case Side::THREE: ast << "Three: "; break;
case Side::FOUR: ast << "Four: "; break;
case Side::FIVE: ast << "Five: "; break;
case Side::SIX: ast << "Six: "; break;
}
ast << strValue << '(' << h[n].value << ')' << endl;
}
return ast.str();
}
In main function you have to clear histogram before next rollDice
case 'r': case 'R':
for (Bar& b : histogram) {
b.value = 0;
}
rollDice(histogram, 100);
break;
Full version
#include <iostream>
#include <iomanip>
#include <string>
#include <random>
#include <sstream>
using namespace std;
enum class Side {
ONE, TWO, THREE, FOUR, FIVE, SIX
};
struct Bar {
int value;
Side label;
};
void rollDice(Bar h[], int count = 100) {
default_random_engine en;
uniform_int_distribution<> dist{1,6};
for( int n = 0; n <= count; n++) {
cout << dist(en) << endl;
const auto index = dist(en) - 1;
++h[index].value;
}
};
string getHistogram(Bar h[], char c = '*') {
stringstream ast;
for( int n = 0; n <= 5; n++) {
const string strValue = string(h[n].value, c);
switch (h[n].label)
{
case Side::ONE: ast << "One: "; break;
case Side::TWO: ast << "Two: "; break;
case Side::THREE: ast << "Three: "; break;
case Side::FOUR: ast << "Four: "; break;
case Side::FIVE: ast << "Five: "; break;
case Side::SIX: ast << "Six: "; break;
}
ast << strValue << '(' << h[n].value << ')' << endl;
}
return ast.str();
}
int main (){
Bar histogram[] = {
{0, Side::ONE},
{0, Side::TWO},
{0, Side::THREE},
{0, Side::FOUR},
{0, Side::FIVE},
{0, Side::SIX}
};
char choice;
do {
cout << "DICE ROLLING SIMULATION" << endl
<<"===============================" << endl
<< "r. Roll Dice" << endl
<< "h. Display histogram" << endl
<< "q. Quit program\n" << endl
<< "\nEnter your choice:" << endl;
// Reading a single character using the scanner
cin >> choice;
switch(choice) {
case 'r': case 'R':
for (Bar& b : histogram) {
b.value = 0;
}
rollDice(histogram, 100);
break;
case 'h': case 'H':
cout << getHistogram(histogram, '*') << endl;
break;
case 'q': case 'Q':
cout << "Good bye\n" << endl;
break;
default:
cout << "Invalid choice\n" << endl;
}
} while(choice != 'q');
}
I know this program is long, but any help would be much appreciated. When I try to read in an object from a file, I always end up with a segmentation fault. I've commented the line where the problem is. It's under 'case d' in the switch statement.
The objects I'm writing out the text file is polymorphic, which might be part of why I'm getting segmentation faults, but I'm not sure.
#include <iostream>
#include <string.h>
#include <vector>
#include <unistd.h>
#include <fstream>
#include "employee.h"
int main(int argc, char* argv[])
{
std::string command, choice, name;
float wage, percent;
int hours = 1;
std::ofstream file;
std::ifstream infile;
std::vector<Employee*> database;
while (command[0] != 'q')
{
clear();
menu();
std::cout << "Enter command: ";
std::cin >> command;
try
{
if(command.size() != 1)
throw "Not a character.";
else
{
switch(command[0])
{
case 'n':
std::cout << "Enter the name of the new employee: ";
//std::cin >> name;
std::cin.clear();
std::cin.ignore();
getline(std::cin, name);
std::cout << "Hourly (h) or salaried (s): ";
std::cin >> choice;
if(choice.size() != 1)
throw "Not a valid choice.";
else
if(choice == "h")
{
std::cout << "Enter hourly wage: ";
std::cin >> wage;
if(!wage)
throw "Not an option";
else{
Employee *emp = new PartTimeEmployee(wage, name);
database.push_back(emp);
continueWithProgram();
break;
}
}else if(choice == "s")
{
std::cout << "Enter salaried wage: ";
std::cin >> wage;
if(!wage)
throw "Not an option";
else{
Employee *emp = new FullTimeEmployee(wage, name);
database.push_back(emp);
continueWithProgram();
break;
}
}else{
throw "Not an option";
}
case 'c':
if(database.size() < 1)
throw "No employees in database.";
else
{
for(int i = 0; i < database.size(); i++)
{
std::cout << "Enter number of hours worked by " << database[i]->getName() << ": ";
std::cin >> hours;
std::cout << "Pay: $" << database[i]->computePay(hours) << std::endl;
}
continueWithProgram();
}
break;
case 'r':
std::cout << "Enter percentage to increase: ";
std::cin >> percent;
std::cout << "\nNew Wages\n---------" << std::endl;
for(int i = 0; i < database.size(); i++)
{
database[i]->raiseWage(percent);
std::cout << database[i]->getName() << "\t\t" << "$" << database[i]->toString(database[i]->getWage()) << std::endl;
}
continueWithProgram();
break;
case 'p':
std::cout << "\nEmployee Database: " << database[0]->count << " Personnel\n-----------------\n";
for(int i = 0; i < database.size(); i++)
{
std::cout << database[i]->getName() << std::endl;
}
continueWithProgram();
break;
case 'd':
infile.open("emp.txt", std::ios::in);
Employee *temp;
if(infile.is_open())
{
while(!infile.eof())
{
infile >> *temp; // PROBLEM IS HERE...
database.push_back(temp);
}
}else{
std::cout << "Error occured. File not found." << std::endl;
}
infile.close();
std::cout << "*Data has been downloaded*" << std::endl;
continueWithProgram();
break;
case 'u':
file.open("emp.txt", std::ios::trunc);
if(file.is_open()){
for(int i = 0; i < database.size(); i++)
file << *database[i];
}
file.close();
std::cout << "*Data has been uploaded*\n";
continueWithProgram();
break;
default:
if(command[0] == 'q')
break;
else
{
throw "Not a command";
break;
}
}
}
}catch(const char* message)
{
std::cout << message << std::endl;
std::cin.clear();
std::cin.ignore();
continueWithProgram();
}
catch(...)
{
std::cout << "Error occured." << std::endl;
std::cin.clear();
std::cin.ignore();
continueWithProgram();
}
}
return 0;
}
______________________________________________________-
Header File:
*This is where the operator overload is, which I'm sure is not part of the problem.
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include <unistd.h>
class Employee
{
protected:
float wage;
std::string name;
public:
static int count;
Employee(float wage, std::string name)
{
this->wage = wage;
this->name = name;
count++;
}
virtual float getWage() = 0;
virtual void setWage(float wage) = 0;
virtual float computePay(int hours = 0) = 0;
virtual float raiseWage(float percent = 0) = 0;
virtual std::string toString(int value) = 0;
std::string getName(){return name;}
void setName(std::string name){this->name = name;}
friend std::ofstream& operator<<(std::ofstream &out, Employee &emp);
friend std::ifstream& operator>>(std::ifstream &in, Employee &emp);
};
class FullTimeEmployee : public Employee
{
public:
FullTimeEmployee(float annualSalary, std::string name) : Employee(annualSalary, name)
{
getWage();
}
float getWage() {return wage;}
void setWage(float wage) {this->wage = wage;}
float computePay(int hours = 0) {return (wage / 52);}
std::string toString(int value){return std::to_string(value) + "/year";}
float raiseWage(float percent = 0)
{
wage = wage + (wage * (percent / 100));
return wage;
}
};
class PartTimeEmployee : public Employee
{
public:
PartTimeEmployee(float wage, std::string name) : Employee(wage, name)
{
getWage();
}
float getWage() {return wage;}
void setWage(float wage) {this->wage = wage;}
std::string toString(int value){return std::to_string(value) + "/hour";}
float computePay(int hours)
{
if(hours <= 40)
return wage * hours;
else
{
hours -= 40;
return ((wage * 40) + ((wage * 1.5) * hours));
}
}
float raiseWage(float percent = 0)
{
wage = wage + (wage * (percent / 100));
return wage;
}
};
std::ofstream& operator<<(std::ofstream &out, Employee &emp)
{
out << emp.name << std::endl << emp.wage << std::endl;
return out;
}
std::ifstream& operator>>(std::ifstream &in, Employee &emp)
{
in >> emp.name;
in >> emp.wage;
return in;
}
int Employee::count = 0;
void menu()
{
std::cout << "-----------------------------------" << std::endl;
std::cout << "|Commmands: n - New Employee |" << std::endl;
std::cout << "| c - Compute Paychecks |" << std::endl;
std::cout << "| r - Raise Wages |" << std::endl;
std::cout << "| p - Print Records |" << std::endl;
std::cout << "| d - Download Data |" << std::endl;
std::cout << "| u - Upload Data |" << std::endl;
std::cout << "| q - Quit |" << std::endl;
std::cout << "-----------------------------------" << std::endl;
}
void clear() {std::cout << "\033[2J\033[1;1H";}
int continueWithProgram()
{
std::string anw;
while(anw[0] != 'y' || anw[0] != 'Y')
{
std::cout << "\nDo you want to continue?(y/n) ";
std::cin >> anw;
return 0;
if(anw.size() != 1)
{
throw "Not a character";
}else if (anw[0] == 'n' || anw[0] == 'N')
exit(0);
}
}
You must add subtype information (Ex: 'f' or 'p', denoting partime and fulltime) somewhere in your file-format. If you really want do deserialize a Pointer from the file you might change both operators.
(However I strongly recommend to use an other approach and fix memory leaks):
operator<< should first print an extra line consisting of just one character denoting the subtype of Employ that is serialized.
using PEmployee = *Employee;
std::ifstream& operator>>(std::ifstream &in, PEmployee &emp)
{
char subType;
float wage;
std::string name;
in >> subType;
in >> name; // FIXIT - we suspect file in not eof
in >> wage;
if(subType == 'f')
emp = new FullTimeEmploy(wage, name);
else
emp = new PartTimeEmploy(wage, name); // FIXIT: we suspect subType == 'p'
return in;
}
And in the while-Loop beneath case 'd': you should call the new operator by infile >> temp;
I hope this works and answers your question.
I do not recommend this approach, calling new as side-effect from an operator rises the question who (which part of the Prog) is responsible for cleaning up (i.e. calling delete). It might work in small Progs but usually it will results in a mess.
Memory leaks: If you use new and delete, be always aware where in Your Prog the allocated memory will be freed. It is not done by the Run-time environment, C++ is not a managed language. HINT: std::vector<Employee*> wont call delete on the stored pointers, it just frees its workload (Employee*). It's the pointer itself not the pointee, i.e. the Object you accuired with new .
PS:
A more straight forward aproach is to change only the operator<< and evaluate the subtype inside the while-Loop beneath case 'd': First read the subtype-char, switch subtype, create the according subclass (Ex: temp = new PartTimeEmployee(); and call the unchanged operator>> with the newly created temp.
For this approach you'll need standart Constructors like PartTimeEmployee::PartTimeEmployee(); for all your subclasses.
I am attempting to build a hotel reservation program in C++. however, I have an issue. I keep getting the above error message and I can't seem to find a fix.
Please provide some assistance. Anything would be greatly appreciated. Below is what I have written thus far.
using namespace std;
class HotelRoom{
private:
int roomnum; //Room numbers
int roomcap; //Room capacity
int roomoccuoystst = 0;
int maxperperroom;
double dailyrate;
public:
HotelRoom()
{
roomcap = 0;
maxperperroom = 2;
dailyrate = 175;
}
int gettotal = 0;
int gettotallist = 0;
string room;
string guestroom,message;
void viewrooms()
{
char viewselect, back;
cout<<"Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : " ;
cin>>viewselect;
switch(viewselect)
{
case '1':
viewaddromm();
break;
case '2':
viewresromm();
break;
default:
cout<<"Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : ";
cin>>back;
switch(back)
{
case '1':
viewrooms();
break;
case '2':
hotelmenu();
break;
default:
exitpro();
}
}
}
void viewresromm()
{
int occup,rmchoose,up;
string roomtochange, items;
string guestroomdb;
int newaccupancy;
char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
ifstream getdatafromaddroom; //creation of the ifstream object
getdatafromaddroom.open("reserveroom.out");
if(getdatafromaddroom.fail()) //if statement used for error checking
{
cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file
}
cout<<endl;
cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl;
cout<<"-------------------------------------------------------"<<endl;
string items;
while(!getdatafromaddroom.eof())
{
// getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
//cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if( getdatafromaddroom.eof() ) break;
cout<<items<<endl;
}
for(int getlist = 0; getlist < gettotallist; getlist++ )
{
cout<<items<<endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
}
}
void viewaddromm()
{
int occup,rmchoose,up;
string roomtochange;
string guestroomdb;
int newaccupancy;
char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
fstream getdatafromaddroom; //creation of the ifstream object
getdatafromaddroom.open("addroom.out");
if(getdatafromaddroom.fail()) //if statement used for error checking
{
cout<<"Could not open file"<<endl; //message that will be printed if the program cannot open the file
}
cout<<endl;
cout<<"First Name"<<'-'<<"Last Name"<<'-'<<"Nationality"<<'-'<<"Guest(s)"<<'-'<<"Room #"<<endl;
cout<<"-------------------------------------------------------"<<endl;
string items;
while(!getdatafromaddroom.eof())
{
// getdatafromaddroom >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
//cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if( getdatafromaddroom.eof() ) break;
cout<<items<<endl;
}
for(int getlist = 0; getlist < gettotallist; getlist++ )
{
cout<<items<<endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<' '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<' '<<setw(9)<<guestroomdb<<endl;
}
}
void exitpro()
{
cout<<"Program closing......Goodbye"<<endl;
system("Pause");
exit(0);
}
menu()
{
char menuchoice;
cout<<"[-------------------------------------------------------]"<<endl;
cout<<"[-Welcome to the hotel booking and reseration menu-]"<<endl;
cout<<"[--------------------------------------------------------]"<<endl;
cout<<setw(30)<<"Addroom -- 1"<<endl;
cout<<setw(32)<<"Reserve a room -- 2"<<endl;
cout<<setw(34)<<" Modify a room -- 3"<<endl;
cout<<setw(36)<<"View roms -- 4"<<endl;
cout<<setw(38)<<" Exist -- 5"<<endl;
cin>>menuchoice;
switch(menuchoice)
{
case '1':
Addroom();
break;
case '2':
reserveroom();
break;
case '3':
modifyroom();
break;
case '4':
viewrooms();
break;
}
}
};
#endif
#include<string>
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
class HotelRoom
{
private:
int roomnum; // Room numbers
int roomcap; // Room capacity
int roomoccuoystst = 0;
int maxperperroom;
double dailyrate;
public:
HotelRoom()
{
roomcap = 0;
maxperperroom = 2;
dailyrate = 175;
}
int gettotal = 0;
int gettotallist = 0;
string room;
string guestroom, message;
void viewrooms()
{
char viewselect, back;
cout << "Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : ";
cin >> viewselect;
switch (viewselect)
{
case '1':
viewaddromm();
break;
case '2':
viewresromm();
break;
default:
cout <<
"Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : ";
cin >> back;
switch (back)
{
case '1':
viewrooms();
break;
case '2':
menu();
break;
default:
exitpro();
}
}
}
void viewresromm()
{
string roomtochange, items;
string guestroomdb;
// int newaccupancy;
// char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
ifstream getdatafromaddroom; // creation of the ifstream object
getdatafromaddroom.open("reserveroom.out");
if (getdatafromaddroom.fail()) // if statement used for error
// checking
{
cout << "Could not open file" << endl; // message that will be
// printed if the program
// cannot open the file
return;
}
cout << endl;
cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
'-' << "Room #" << endl;
cout << "-------------------------------------------------------" << endl;
// string items;
while (!getdatafromaddroom.eof())
{
// getdatafromaddroom
// >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if (getdatafromaddroom.eof())
break;
cout << items << endl;
}
for (int getlist = 0; getlist < gettotallist; getlist++)
{
cout << items << endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
}
}
void viewaddromm()
{
// int occup,rmchoose,up;
string roomtochange;
string guestroomdb;
// int newaccupancy;
// char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
fstream getdatafromaddroom; // creation of the ifstream object
getdatafromaddroom.open("addroom.out");
if (getdatafromaddroom.fail()) // if statement used for error
// checking
{
cout << "Could not open file" << endl; // message that will be
// printed if the program
// cannot open the file
return;
}
cout << endl;
cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
'-' << "Room #" << endl;
cout << "-------------------------------------------------------" << endl;
string items;
while (!getdatafromaddroom.eof())
{
// getdatafromaddroom
// >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if (getdatafromaddroom.eof())
break;
cout << items << endl;
}
for (int getlist = 0; getlist < gettotallist; getlist++)
{
cout << items << endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
}
}
void exitpro()
{
cout << "Program closing......Goodbye" << endl;
// system("Pause");
exit(0);
}
void Addroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void reserveroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void modifyroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void menu()
{
while (true)
{
char menuchoice;
cout << "[-------------------------------------------------------]" << endl;
cout << "[-Welcome to the hotel booking and reseration menu-]" << endl;
cout << "[--------------------------------------------------------]" << endl;
cout << setw(30) << "Addroom -- 1" << endl;
cout << setw(30) << "Reserve a room -- 2" << endl;
cout << setw(30) << "Modify a room -- 3" << endl;
cout << setw(30) << "View rooms -- 4" << endl;
cout << setw(30) << "Exit -- 5" << endl;
cin >> menuchoice;
switch (menuchoice)
{
case '1':
Addroom();
break;
case '2':
reserveroom();
break;
case '3':
modifyroom();
break;
case '4':
viewrooms();
break;
case '5':
exitpro();
}
}
}
};
int main()
{
try
{
HotelRoom room;
room.menu();
}
catch(std::logic_error * ex)
{
std::cout << ex->what();
}
}
you have a lot more to go with this project. I've fixed the portion you specifically asked about and its now a runninng application with somewhat approperate diagnostics. I'm not going to get too deep into how this language works but you have several functions that were not implimented, missing return types, and just general logic errors like trying to use a file after you determined it wasnt open. it runs now, and you can get a clear indication of what you need to complete. You also had several unused varables.
i added , at minimal,
void Addroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void reserveroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void modifyroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
and a return type to menu.
`void menu()
you cannot call functions you have not yet written, and all functions have a return type even if they return nothing.
Good luck!
Novice C++ user trying to practice program building. The point of this program is just simple name storage with vectors.
My previous program https://pastebin.com/MG1hHzgK works perfectly fine for just adding first names.
This upgraded version is supposed to have an input of First Last names then it is converted into Last, First name before being added to the list.
My problem is that after I input names, they arent added to the list. The differences between my previous program and current one are all in the function addNames and to me it looks correct when its obviously not.
Any hints or help is greatly appreciated.
#include <conio.h>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Prototypes
string addNames(vector <string>& nameList);
string removeName(vector <string>& nameList);
int findName (vector <string>& nameList);
void showList(vector <string>& nameList);
void commandList(vector <string>& nameList);
void inputCall(vector <string>& nameList);
void sortList(vector <string>& nameList);
int main()
{
vector <string> nameList;
commandList(nameList);
}
void commandList(vector <string>& nameList)
{
cout << "\nPress any key to continue..." << endl;
getch();
system("cls");
cout << "Enter a Command " << endl;
cout << "<A> - Add names to the list" << endl;
cout << "<R> - Remove a name from the list" << endl;
cout << "<F> - Search for a name on the list" << endl;
cout << "<L> - Show current state of the list" << endl;
cout << "<S> - Sort the list" << endl;
cout << "<Q> - Ends the program" << endl;
inputCall(nameList);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
string addNames(vector <string>& nameList)
{
string input;
int pos = input.find(' ');
nameList.clear();
for (;true;)
{
cout << endl;
cout << "Enter a Name or 'Stop' to end name entry: " << endl;
getline(cin, input);
if (input == "Stop" || input == "stop"){
commandList(nameList);
} else if(pos != -1) {
string first = input.substr(0, pos);
string last = input.substr(pos + 1);
input = last + "," + first;
nameList.push_back(input);
commandList(nameList);
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
string removeName(vector <string>& nameList)
{
string x;
cout << endl;
cout << "Enter the name to remove: " << endl;
cin >> x;
for (int i=0; i < nameList.size(); ++i) {
if (nameList[i]== x) nameList[i]="";
}
commandList(nameList);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
int findName (vector <string>& nameList)
{
string target;
int i, x=0;
int p=0;
cout << endl;
cout << "Enter a name to search for: " << endl;
cin >> target;
if (target == "Quit" || target == "quit") {exit(0);
}
for (int i=0; i < nameList.size(); i++)
{
if (nameList[i] == target)
{
cout << endl;
cout << "The entered name is listed as #" << p+1 << '.' << endl;
commandList(nameList);
return p;
}
if (nameList[i] == "") {
p--;
}
p++;
}
cout << endl;
cout << "Name not found!" << endl;
commandList(nameList);
return -1;
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
void showList(vector <string>& nameList)
{
cout << endl;
cout << "The current state of the list is: " <<endl;
for (int i=0; i<nameList.size(); i++)
if(nameList[i] !="")
cout << nameList[i] << endl;
commandList(nameList);
}
void sortList(vector <string>& nameList)
{
string temp;
for (int i=0; i < nameList.size()-1; i++)
{
for (int j=0; j < (nameList.size()-i-1); j++)
{
if (nameList[j] > nameList[j+1])
{
temp = nameList[j];
nameList[j] = nameList[j+1];
nameList[j+1] = temp;
}
}
}
cout << endl;
cout << "The list has been sorted alphabetically." << endl;
commandList(nameList);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------
void inputCall(vector <string>& nameList) // Function to complement the menu for switch casing
{
bool running = true;
char input;
do {
input = getch();
switch(input)
{
case 'a': addNames(nameList);break;
case 'A': addNames(nameList);break;
case 's': sortList(nameList);break;
case 'S': sortList(nameList);break;
case 'l': showList(nameList);break;
case 'L': showList(nameList);break;
case 'f': findName(nameList);break;
case 'F': findName(nameList);break;
case 'r': removeName(nameList);break;
case 'R': removeName(nameList);break;
case 'q': exit(0);break;
case 'Q': exit(0);break;
default : cout << "Unknown Command: Enter a command from the menu." << endl; continue;
}
} while (running);
}
if you insert
pos = input.find(' '); in else { } just above ( if(pos != -1) )
Your code will work
I am new to c++ and and am working on a program that has is a simple dvd rental program. I am having issues with case 3 & 4 specifically. Maybe I am misunderstanding the purpose behind sizeof. What I am trying to have it do is tell if the char array is empty and if it is allow the user to check it out by putting their name in and if it is not available give them a response saying that it is not available. case 4 should do the opposite and allow them to check it in. Any suggestions would be greatly appreciated.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <limits>
using namespace std;
const int arrSize = 5;
struct dvdStruct //distance struct
{
int id;
char title[51] = { 0 };
char rating[5] = { 0 };
double price;
char borrower[51] = { 0 };
} dvd;
dvdStruct dvds[arrSize] = {};
int userSelection; //intput variable for main menu selection
int borrowId (0);
int borrowIdReturn(0);
//void initalize();
int main() {
int size(0);
dvds[0].id = 1;
dvds[1].id = 2;
dvds[2].id = 3;
dvds[3].id = 4;
dvds[4].id = 5;
strcpy(dvds[0].title, "Fast 1");
strcpy(dvds[1].title, "Fast 2");
strcpy(dvds[2].title, "Fast 3");
strcpy(dvds[3].title, "Fast 4");
strcpy(dvds[4].title, "Fast 5");
strcpy(dvds[0].rating, "PG - 13");
strcpy(dvds[1].rating, "PG - 13");
strcpy(dvds[2].rating, "PG - 13");
strcpy(dvds[3].rating, "PG - 13");
strcpy(dvds[4].rating, "PG - 13");
dvds[0].price = '19.1';
dvds[1].price = '19.2';
dvds[2].price = '19.3';
dvds[3].price = '19.4';
dvds[4].price = '19.5';
strcpy(dvds[0].borrower, "");
cout << strlen(dvds[0].borrower) << endl;
strcpy(dvds[1].borrower, "\0");
strcpy(dvds[2].borrower, "\0");
strcpy(dvds[3].borrower, "\0");
strcpy(dvds[4].borrower, "\0");
do {
cout << "1.Display All DVD’s" << endl << "2.Display DVD Detail" << endl << "3.Check Out a DVD" << endl << "4.Check In a DVD" << endl << "5.Exit" << endl;
cin >> userSelection; //Input from the user.
switch (userSelection)
{
case 1:
for (int i = 0; i < arrSize; i++)
{
std::cout << dvds[i].title << "' " << dvds[i].rating << " " << dvds[i].borrower << endl;
}
system("pause");
system("CLS");
break;
case 2:
int dvdNum;
cout << "Enter a DVD number:";
cin >> dvdNum;
std::cout << dvds[dvdNum - 1].title << "' " << dvds[dvdNum - 1].rating << endl;
system("pause");
system("CLS");
break;
case 3:
cout << "Enter and id:";
cin >> borrowId;
if (strlen(dvds[borrowId-1].borrower) == 0)
{
cout << "Enter your name: ";
cin >> dvds[borrowId-1].borrower;
}
else
{
cout << "This dvd is not available" << endl;
}
system("pause");
system("CLS");
break;
case 4:
cout << "Enter and id:";
cin >> borrowIdReturn;
if (strlen(dvds[borrowIdReturn - 1].borrower) == 0)
{
cout << "This dvd is available" << endl;
}
else
{
cout << "Your DVD has been returned " << endl;
strcpy(dvds[borrowIdReturn - 1].borrower, "\0");
}
system("pause");
system("CLS");
break;
case 5:
return 0;
break;
}
} while (userSelection == 1 || userSelection == 2 || userSelection == 3 || userSelection == 4);
}
sizeof() gives you the size of an object. The size of the object is always the same, no matter what's in the object. In fact, sizeof() is calculated at compile time, and its value could not be affected, in any way, by whatever happens at runtime.
C++ code should use std::string, instead of char arrays, in most cases. std::string's empty() method indicates whether the string is empty.
If you still insist on working with C-style char arrays, and C-style '\0' terminated strings, use the C strlen() function to check if the character array contains nothing but a leading '\0', indicating an empty string.