Then it will reset to the questions number 1.
I wanted to implement health points system in my code, so that if your hp goes to 0 (zero) when choosing the wrong answer, it will start to question number 1
I'm new to c++ and doesn't know much about it but if you have any recommendation how to improve my coding i'm happy to take your advice.
Code:
void questions()
{
int score, end, hp = 1;
char ans[28];
cout <<"\t\tHEALTH POINTS= " << hp <<"\n\n";
cout << "1.What thing has to be broken before it can be used?\n\n"; //Questions
cout << "[A]-Egg,";
cout << " [B]-Heart,"; //Choices
cout << " [C]-Cube,";
cout << " [D]-Case";
cout << "\n\n";
cout << "YOUR ANSWER IS: ";
cin >> ans[1];
if (ans[1]=='a'||ans[1]=='A') //This will decide if the input is correct
{
cout << "YOUR ANSWER IS CORRECT: [A] - Egg \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "2.Jimmy's mother had three children. The first was called April, \nthe second was called May. What was the name of the third?\n";
cout << "[A]-May,";
cout << " [B]-Jimmy,";
cout << " [C]-April,";
cout << " [D]-Third";
cout << "\n\n";
cout << "Your Answer is: ";
cin >> ans[2];
if (ans[2]=='b'||ans[2]=='B')
{
cout << "YOUR ANSWER IS CORRECT: [B] - Jimmy \n\n";
score++;
}
else
{
cout <<"\nWRONG! ";
cout <<"YOU NOW HAVE "<< (hp=(hp-1)) <<" HP LEFT\n\n";
}
cout << "\n\t\t YOUR SCORE IS:" << score << "/2, ";
cout <<"YOU HAVE "<< hp <<" HP LEFT\n\n";
cout << endl;
cout <<"\n\t\t PRESS ANY KEY TO GO BACK TO CHOICES...";
getch(); //Holds the screen
system("cls");
questions();
One way to improve your approach might be implementing some sort of function to handle asking a question, with predefined choices, and getting an answer back. Instead of writing the code out twice like you do above to ask two questions, you could call the same function twice, passing in the different arguments.
Related
So I'm writing this spinoff game of Paperboy as a class project. If I wanted to I could say I'm finished and turn it in but I want it to have a professional touch to it. My game consists of different modes: easy and hard. However I have not implemented the hard mode yet.
Anyway, here is my code
void easyMode() {
string playerName;
int numNewspapers, numDelivered = 0, numMissed = 0, score = 0;
cout << "Enter Your Player Name: ";
cin >> playerName;
cout << "\nEnter How Many Newspapers That Need To Be Delivered: ";
cin >> numNewspapers;
cout << "\n\nYou have " << numNewspapers << " newspapers to deliver!\n\n";
cout << "Time To Deliver !!\n\n";
cout << "*===================================*\n\n";
//cout << string(50, '\n');
while (numDelivered < numNewspapers) {
int outcome = RandomNumberEasy();
cout << "*===================================*\n\n";
cout << "Delivering Newspaper...\n\n";
// Game Sequence
//*===================================*
// Delivered Successfully
//*===================================*
if (outcome <= 3 || outcome > 7) {
cout << "You Successfully Delivered The Newspaper.\n\n";
numDelivered++;
score = score + 15;
cout << "Your score is " << score << " points!\n\n";
}
// Delivery Failed
//*===================================*
else {
cout << "The Neighbor's Dog Chased You. Delivered Paper Didn't Quite Land On Step\n\n";
numDelivered++;
numMissed++;
score = score + 5;
cout << "Your score is " << score << " points!\n";
}
cout << "\n";
sleep(1);
}
// END GAME
//*===================================*
if (numDelivered == numNewspapers) {
int SuccDeliver = numDelivered - numMissed;
cout << "*===================================*\n\n";
cout << "Congratulations, " << playerName << "!\n\n";
cout << "Your Final Score Is: " << score;
cout << "\n\nYou missed " << numMissed << " Newspapers And Delivered " << SuccDeliver << " Newspapers\n\n";
}
}
As you can see I do have the sleep function in there, but when I run my program, it waits a long time and the outputs every iteration all at once. I want it to wait in between each iteration but I can't seem to get it to work.
Any help is appreciated!
The problem seems to be that the output buffer is not being flushed. A way to do it is to use cout << endl instead of cout << "\n". Mainly, this part:
cout << "\n";
sleep(1);
Should be like this:
cout << endl;
sleep(1);
And that should fix it!
its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.
i'm trying to set up a simple flight booking system program, but my second bit of cin code is not calling for input when i run the program. Unlike the initial cin that requires your name initially. the program just runs and returns 0. I'm a beginner at c++ and i know this is a simple fix so please be understanding . Thank you any guidance will be greatly appreciated.
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int name;
int Seatnumber;
int optionnumber = 1-5 ;
std::string out_string;
std::stringstream ss;
ss << optionnumber;
out_string = ss.str();
cout << "Welcome to the COS1511 Flight Booking System" "\n" << endl;
cout << "Enter full name : " << endl;
cin >> name ; "\n";
cout << "\n" "The Available travel times for flights are:" << endl;
cout << " Depart Arrive" << endl;
cout << "1. 7.00 9.30" << endl;
cout << "2. 9.00 11.30" << endl;
cout << "3. 11.00 13.30" << endl;
cout << "4. 13.00 15.30" << endl;
cout << "5. 15.00 17.30" << endl;
cout << "Choose the time by entering the option number from the displayed list : " << endl;
cin >> optionnumber ;
if (optionnumber == 1-5){
cout << "\n" "The available seats for are as follows " << endl;
}
else
cout << "Incorrect option! Please Choose from 1-5 " << endl;
cout << "First Class(1920)" << endl;
cout << "|A1||A2||A3|----|A4||A5||A6|" << endl;
cout << "|B1||B2||B3|----|B4||B5||B6|" << endl;
cout << "|C1||C2||C3|----|C4||C5||C6|" << endl;
cout << "|D1||D2||D3|----|D4||D5||D6|" << endl;
cout << "| Economy Class(1600)" << endl;
cout << "|E1||E2||E3|----|E4||E5||E6|" << endl;
cout << "|F1||F2||F3|----|F4||F5||F6|" << endl;
cout << "|G1||G2||G3|----|G4||G5||G6|" << endl;
cout << "|H1||H2||H3|----|H4||H5||H6|" << endl;
cout << "|I1||I2|" << endl;
cout << "Please Key in a seat number to choose a seat(eg: A2)" << endl;
cin >> Seatnumber;
}
prompt the user to enter their name.
Then display a menu showing the available times for the flight.
the user can choose a preferred departure time(option 1-5)
the option selected should be validated for 1-5
if the user entered the correct time a seating arrangement for that particular flight time should be displayed to the next user for the user to choose a seat.
Warning
int optionnumber = 1-5 ;
does
int optionnumber = -4 ;
and
if (optionnumber == 1-5){
does
if (optionnumber == -4){
but you wanted if ((optionnumber >= 1) && (optionnumber <= 5))
if the user entered the correct time a seating arrangement for that particular flight time should be displayed to the next user for the user to choose a seat.
No, whatever the result of the test above you continue and write "First Class(1920)" etc so even when the choice is invalid
in
cin >> name ; "\n";
what did you expect about the "\n" ?
I encourage you to check the read success, currently if the user does not enter an integer you do not know that
But are you sure the name must be an integer ? Probably it must be s string
out_string is unused, it can be removed
Visibly Seatnumber is not an int but a string (A1 ...)
you probably want to loop until a valid time is enter, also fixing the other problems a solution can be :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
string Seatnumber;
int optionnumber;
cout << "Welcome to the COS1511 Flight Booking System" "\n" << endl;
cout << "Enter full name : " << endl;
if (!(cin >> name))
// EOF (input from a file)
return -1;
cout << "\n" "The Available travel times for flights are:" << endl;
cout << " Depart Arrive" << endl;
cout << "1. 7.00 9.30" << endl;
cout << "2. 9.00 11.30" << endl;
cout << "3. 11.00 13.30" << endl;
cout << "4. 13.00 15.30" << endl;
cout << "5. 15.00 17.30" << endl;
cout << "Choose the time by entering the option number from the displayed list : " << endl;
for (;;) {
if (!(cin >> optionnumber)) {
// not an int
cin.clear(); // clear error
string s;
// flush invalid input
if (!(cin >> s))
// EOF (input from a file)
return -1;
}
else if ((optionnumber >= 1) && (optionnumber <= 5))
// valid choice
break;
cout << "Incorrect option! Please Choose from 1-5 " << endl;
}
cout << "\n" "The available seats for are as follows " << endl;
cout << "First Class(1920)" << endl;
cout << "|A1||A2||A3|----|A4||A5||A6|" << endl;
cout << "|B1||B2||B3|----|B4||B5||B6|" << endl;
cout << "|C1||C2||C3|----|C4||C5||C6|" << endl;
cout << "|D1||D2||D3|----|D4||D5||D6|" << endl;
cout << "| Economy Class(1600)" << endl;
cout << "|E1||E2||E3|----|E4||E5||E6|" << endl;
cout << "|F1||F2||F3|----|F4||F5||F6|" << endl;
cout << "|G1||G2||G3|----|G4||G5||G6|" << endl;
cout << "|H1||H2||H3|----|H4||H5||H6|" << endl;
cout << "|I1||I2|" << endl;
cout << "Please Key in a seat number to choose a seat(eg: A2)" << endl;
cin >> Seatnumber;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall cc.cc
pi#raspberrypi:/tmp $ ./a.out
Welcome to the COS1511 Flight Booking System
Enter full name :
bruno
The Available travel times for flights are:
Depart Arrive
1. 7.00 9.30
2. 9.00 11.30
3. 11.00 13.30
4. 13.00 15.30
5. 15.00 17.30
Choose the time by entering the option number from the displayed list :
aze
Incorrect option! Please Choose from 1-5
7
Incorrect option! Please Choose from 1-5
2
The available seats for are as follows
First Class(1920)
|A1||A2||A3|----|A4||A5||A6|
|B1||B2||B3|----|B4||B5||B6|
|C1||C2||C3|----|C4||C5||C6|
|D1||D2||D3|----|D4||D5||D6|
| Economy Class(1600)
|E1||E2||E3|----|E4||E5||E6|
|F1||F2||F3|----|F4||F5||F6|
|G1||G2||G3|----|G4||G5||G6|
|H1||H2||H3|----|H4||H5||H6|
|I1||I2|
Please Key in a seat number to choose a seat(eg: A2)
qsd
pi#raspberrypi:/tmp $
Note entering the name with cin >> name does not allow it to contain several names separated by a space, to allow composed name getline can be used
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am supposed to make a class AddressBook containing a class called Person. My program almost, works, except when I add a person, it doesn't remember it in the next iteration of the Command menu and Display All turns up "There are 0 people in your address book." What is wrong with my code?
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
class Person
{
public:
char firstName[15];
char lastName[15];
char personID[15];
};
Person entries[100];
unsigned int total;
AddressBook()
{
total = 0;
}
void AddPerson()
{
cout << "This is entry number " << (total + 1) << " in your address book. " << endl;
cout << "What shall we put for the first and last name? Limit both to under 15 characters. Example: Bob Smith" << endl;
cin >> entries[total].firstName >> entries[total].lastName;
cout << "What is " << entries[total].firstName << " " << entries[total].lastName << "'s ID code?" << endl;
cin >> entries[total].personID;
++total;
cout << "..." << endl << "Successfully Added." << endl;
};
void DisplayPerson(int i)
{
cout << "Entry " << i + 1 << ": " << endl;
cout << "FIRST NAME: " << entries[i].firstName << endl;
cout << "LAST NAME: " << entries[i].lastName << endl;
cout << "ID: " << entries[i].personID << endl;
};
void DisplayEveryone()
{
cout << "You have " << total << " People in your address book." << endl;
for (int i = 0; i < total; ++i)
DisplayPerson(i);
};
void SearchPerson()
{
char lastname[32];
cout << "Please enter the last name of the person you wish to find." << endl;
cin >> lastname;
for (int i = 0; i < total; ++i)
{
if (strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Person Found. " << endl;
DisplayPerson(i);
cout << endl;
}
}
};
};
int main() {
char command;
bool Exit = false;
while (Exit == false)
{
AddressBook Address_Book;
cout << "---------------COMMANDS---------------" << endl;
cout << "A: Add Person To Address Book" << endl;
cout << "S: Search for Person in Address Book" << endl;
cout << "D: Display Everyone In Address Book" << endl << endl;
cout << "Type the letter of your command: ";
cin >> command;
cout << endl;
switch (command) {
case 'A':
case 'a':
Address_Book.AddPerson();
break;
case 'S':
case 's':
Address_Book.SearchPerson();
break;
case 'D':
case 'd':
Address_Book.DisplayEveryone();
break;
default:
cout << "That is not a valid command. Closing Address Book." << endl;
cout << endl;
}
}
}
The reason is that you create a new address book in each iteration of the while loop and throw it away at the end of the iteration:
This
AddressBook Address_Book;
creates a new address book that is "thrown away" when you reach the end of its scope (ie. the end of the loop).
In reality, do you buy a new address book whenever you want to make new entry? No. You first buy the book and then (possibly in a while loop) you add entries. Move the above line outside of the loop.
Your problem is in the declaration of your address book.
Change it to the following:
AddressBook Address_Book;
while (Exit == false) {
//Ask for input and respond.
}
In your version Address_Book is declared at the start of the while loop. This means that every time an iteration of the loop completes and execution returns to the start of the block, a new local Address_Book object is created that has no knowledge of the previous objects data.
I am having trouble getting my while loop to run. I am a very beginner coder and I have made many attempts with no success to make this work. I need help PLEASE!! Please be very specific and with laymen terms with your help since I am new to this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string mystr1;
string mystr2;
cout << "Please provide your first and last name" << endl;
getline (cin, mystr1);
cout << endl;
cout << "Please provide your shipping address" << endl;
getline (cin, mystr2);
cout << endl;
cout << "Hello " << mystr1 << " and welcome to Faulk Couture
Handbags Boutique" << endl; // prints Hello and welcome to Faulk
Couture Handbags Boutique
cout << endl;
cout << "We have a variety of specialty and fashionable handbags to
select from. Please see below for the available products and their
descriptions." << endl;
cout << endl;
cout << "Product 1: Crosby Carryall in black priced at $395. This
sophisticated and spacious Crosby Carryall is a work-to-weekend favorite
and is finished with " << endl;
cout << "bound leather edges, a detachable leather strap and petite
brass turnlocks securing its two zippered compartments."<< endl;
cout << endl;
cout << "Product 2: Prairie satchel with chain nude priced at $450.
Crafted in lightweight pebble leather with a bit of sheen, this
gracefully curved shape distills" <<endl;
cout << "the satchel to its purest form. The simple design is finished
with a slender strap and an elegant chain detail that detaches for a
different look." << endl;
cout << endl;
cout << "Product 3: Faulk Swagger 20 brown priced at $325. This
Statement belting with double-turnlock hardware is one of our most
popular designs with a little bit of “swagger.” "<< endl;
cout << "Named for a bold, brass-trimmed Bonnie Cashin design from 1967,
this very modern carryall in refined pebble leather comes finished with
a detachable strap for crossbody wear." << endl;
cout << endl;
cout << "Product 4: Zip top tote in brown priced at $285. This
sophisticated and light weight in signature canvas with hand-finished
leather trim, this aptly named tote is made for one-the-go ease." <<
endl;
cout << "A modern, flared shape and oversized strap anchors add playful
proportions to its spacious, brightly lined design." << endl;
cout << endl;
cout << "Product 5: Wristlet 24 priced at $175. This striking, feminine
design in polished pebble leather has space enough for a tablet and an
elegant chain that converts it from wristlet to top handle." << endl;
cout << "A dog-leash clip on the strap and an embossed hangtag charm
finish it with signature Faulk Couture Style." << endl;
cout << endl;
double cost, total, amount;
int product;
cout << "Please enter the product number for your bag choice" << endl;
cin >> product;
cout <<"The respective price for this bag is: " << endl;
cin>>cost;
cout<<"Please enter the quantity you would like to purchase for this
bag choice" << endl;
cin>>amount;
total = cost*amount;
cout <<"Your total purchase price for " <<amount<< " qty of product
number " <<product<< " is " <<total<<"."<< endl;
int choice=1;
while (choice==1);
{
cout << "To purchase another bag, please enter 1 (anything else to
quit)" << endl;
cin >> choice;
cout << "Please enter the product number for your next bag choice" <<
endl;
cin >> product;
cout << "The respective price for this bag is: " << endl;
cin >> cost;
cout << "Please enter the quantity you would like to purchase for this
bag choice" << endl;
cin >> amount;
total = cost*amount;
cout <<"Your total purchase price for " <<amount<< " qty of product
number " <<product<< " is " <<total<<"."<< endl;
}
cout << endl;
return 0;
}
You're ending your while loop with a semicolon that's why it isn't entering the while loop
Here is the while loop without the semicolon
while (choice==1) {
cout << "To purchase another bag, please enter 1 (anything else to
quit)" << endl;
cin >> choice;
cout << "Please enter the product number for your next bag choice" <<
endl;
cin >> product;
cout << "The respective price for this bag is: " << endl;
cin >> cost;
cout << "Please enter the quantity you would like to purchase for this
bag choice" << endl;
cin >> amount;
total = cost*amount;
cout <<"Your total purchase price for " <<amount<< " qty of product
number " <<product<< " is " <<total<<"."<< endl;
}