sleep or time delay for C++ Program - c++

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!

Related

Selecting an array value using a random number generator

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.

If variable equal to 0

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.

Why won't my code switch player names correctly after 3 rounds of play?

So in my class I had to make a Numberwang simulation game. Everything works fine except for the fact that after 2 rounds the names don't correlate correctly. It supposed to say "Round 3, Player1 to play first." which it does however player2 comes up as the one to play first.
# include <iostream>
# include <ctime>
# include <cstdlib>
using namespace std;
bool numberwang(int n)
{
if(n < 100 ){
return 1;
} else {
return 0;
}
}
int main()
{
string Firstplayer, Otherplayer;
int rounds;
int counter = 1;
int number;
int win = 18;
int lose= 1;
cout << "Hello, and welcome to Numberwang, the maths quiz that simply everyone is talking about!" << endl;
cout << "What is player 1's name? ";
cin >> Firstplayer;
cout << "What is player 2's name? ";
cin >> Otherplayer;
cout << "How many rounds? ";
cin >> rounds;
cout << "Well, if you're ready, lets play Numberwang!" << endl;
while(counter <= rounds){
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
while(true){
cout << Firstplayer << ": ";
cin >> number;
if(numberwang(number)){
counter++;
if(counter > rounds){
cout << "That's Numberwang!" << endl;
cout << "Final scores: " << Firstplayer << " pulls ahead with " << win << ", and " << Otherplayer << " finishes with " << lose << endl;
break;
}
cout << "That's Numberwang!" << endl;
swap(Firstplayer, Otherplayer);
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
cout << Otherplayer << ": ";
cin >> number;
if(numberwang(number)){
counter++;
if(counter > rounds){
cout << "That's Numberwang!" << endl;
cout << "Final scores: " << Firstplayer << " pulls ahead with " << win << ", and " << Otherplayer << " finishes with " << lose << endl;
break;
}
cout << "That's Numberwang!" << endl;
swap(Firstplayer, Otherplayer);
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
}
}
return 0;
}
After your if-statement (line 61) you say 'Firstplayer' and then you output the 'Otherplayer'. The names do not match.
Blockquote
cout << "Round " << counter << ", " << Firstplayer << " to play first." << endl;
}
cout << Otherplayer << ": ";
cin >> number;

How to print the contents of the C++ keyboard/cin buffer to the console without modification?

I've been working on a program that does quite a bit (at least for me) with cin and its functions, and I've been having a hard time keeping track of what's in the keyboard buffer throughout the program. It's causing me some errors - I was wondering if there was a function or a technique I could use to print the contents of the cin/keyboard buffer to the screen so that I could know what's in it at that point in the program.
I've attached the source code for anyone who's interested. It's homework for one of my classes, so apologies for anyone who sees this as too easy to even bother asking.
// CHAPTER 4 HOMEWORK - PROBLEM 16 - RUNNING THE RACE
/* Write a program that asks for the names of three runners and
the time it took each of them to finish a race. The program
should displace who came in first, second, and third place.
Input validation: only accept positive numbers for the times*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Introduction for the user
cout << "\t\t\t ~ RUNNING THE RACE ~\n"
<< "\t\t\t --------------------\n\n"
<< "Welcome! In this program, you can enter the names of three runners,\n"
<< "and the times at which they finished a race. The program will organize\n"
<< "the names and times from first to last.\n\n"
<< "Are you ready to begin?\n"
<< "Press the Enter key to continue . . . ";
cin.get();
// declare variables and string objects
string runnerName1, runnerName2, runnerName3;
int minutes1, minutes2, minutes3;
double seconds1, seconds2, seconds3;
// RUNNER 1
cout << "\nFirst we'll deal with runner 1.\n"
<< "Please enter runner 1's full name: ";
getline(cin, runnerName1);
cout << "Okay! Now for " << runnerName1 << "'s time.\n"
<< "First, enter " << runnerName1 << "'s minutes (a whole number): ";
cin >> minutes1;
cout << "And now enter " << runnerName1 << "'s seconds: ";
cin >> seconds1;
// RUNNER 2
cout << "\nNext we'll deal with runner 2.\n"
<< "Please enter runner 2's full name: ";
cin.ignore(); // because of the remaining space in the keyboard buffer leftover from the last cin >> statement
getline(cin, runnerName2);
cout << "Good! Now for " << runnerName2 << "'s time.\n"
<< "Enter " << runnerName2 << "'s minutes (a whole number): ";
cin >> minutes2;
cout << "Now enter " << runnerName2 << "'s seconds: ";
cin >> seconds2;
// RUNNER 3
cout << "\nFinally, runner 3.\n"
<< "Please enter runner 3's full name: ";
cin.ignore();
getline(cin, runnerName3);
cout << "What is " << runnerName3 << "'s time?\n"
<< "First, enter " << runnerName3 << "'s minutes (a whole number): ";
cin >> minutes3;
cout << "Now enter " << runnerName3 << "'s seconds: ";
cin >> seconds3;
// display the gathered data in a useful manner
cout << "___________________________________________\n" // border
<< "RESULTS:\n\n"
<< "NAME:\t\t\tTIME:\n";
// make sure any extra seconds entered above 60 gets added to the number of minutes
while (seconds1 >= 60.0)
{
seconds1 -= 60.0;
minutes1 += 1;
}
while (seconds2 >= 60.0)
{
seconds2 -= 60.0;
minutes2 += 1;
}
while (seconds3 >= 60.0)
{
seconds3 -= 60.0;
minutes3 += 1;
}
// now for the results . . .
cout << runnerName1 << "\t" << minutes1 << ":" << seconds1 << endl;
cout << runnerName2 << "\t" << minutes2 << ":" << seconds2 << endl;
cout << runnerName3 << "\t" << minutes3 << ":" << seconds3 << endl;
cin.ignore();
cin.get();
return 0;
}
Also, this was built on VS 2012 Express, for anyone who has multiple versions. I didn't use any windows-exclusive code within the program though (eg system("pause")), so it should work fine with other compilers.

rand number inclining. (C++) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Problems with srand(), C++
Basically, the random number I am generating is inclining in size, everytime it is used inside my while loop. It being random, should't incline and not be random as such.
The variable hit is defined by the random number. But as I said, the random number is not random. Also, as the random number gets bigger it goes over the limit I set for it.
//Code im using for random number :
srand((unsigned)time(0));
hit = rand()%15;
//The subject for the problem :
while (1) {
if (mon1==0) {
cout << "A dragon appears." << endl;
system ("pause");
cout << "Enter 1 to attack and 2 to run away, " <<name << endl;
cin >> act;
if (act==2) {
cout << "You run away. " << endl;
}
if (act==1) {
cout << " You choose to attack! Good luck " << endl;
}
}
if (mon1==1) { // orc
srand((unsigned)time(0));
hit = rand()%15;
ehealth = (100);
cout << " A orc appears" << endl;
system ("pause");
cout << "Enter 1 to attack and 2 to run away, " <<name << endl;
cin >> act;
system ("cls");
if (act==2) {
cout << "You run away. " << endl;
system ("cls");
}
if (act==1) { // ATTACK HERE MAIN ATTACk TESING !!!!!!!!!!!!!!!!!!!!!!! ORC
cout << " You choose to attack! Good luck " << endl;
cout << " Your health is " << health << endl;
cout << " The enemys health is " << ehealth << endl;
cout << " You have 3 abilitys." << endl;
while (1) {
cout << " Press 1 to swipe, 2 to block the enemys attack and 3 to use your special attack" <<endl;
cin >> act1;
system ("cls");
if (act1==1) {
cout << " You swipe the enemy " << endl; // swipe
cout << " You hit for " << hit << endl;
if (wep==1) {
hit = (hit + 4);
cout << " As you are the axe i will add on 4 to that, making " << hit << endl; // axe
}
ehealth = (ehealth - hit);
cout << " The enemys health is " << ehealth << endl;
cout << " Your health is " << health << endl;
system ("pause");
}
if (act1==2) {
cout <<" You block, making you immune to the next attack" << endl; //block
ehit = (0);
//newrand
cout << " Your health is " << health << endl;
cout << " The enemys health is " << ehealth << endl;
}
if (act1==3) {
cout << " Special attack is being worked on BUDDY, GUY, FRIEND!! " << endl;
}
system ("pause");
if (health < 0) {
cout << "You died, sorry!" << endl;
}
if (ehealth < 0) {
cout << " Yay! You killed the enemy!" << endl;
}
if (health == 0) {
cout << "You died, sorry!" << endl;
}
if (ehealth == 0) {
cout << " Yay! You killed the enemy!" << endl;
}
cout << " Now it is the enemys turn! " << endl;
health = ( health - ehit );
cout << " The enemy hits you for a " << ehit << endl;
cout << " Your health is now " << health << endl;
srand((unsigned)time(0));
ehit = rand()%10;
system ("pause");
system ("cls");
}
// END OF ORC
}
}
hit is randomized when the program starts.
If the monster is an orc, hit is re-randomized.
Every time you attach with an axe, hit permanently increases by four.
You probably want to re-randomize hit each time the user attacks as well?
This code causes this behavior:
hit = (hit + 4);
You increase hit always by 4. So you should use a temporary variable instead.
You only need to call srand once, at the start of the program. That "seeds" the random number generator for an unlimited number of rand() calls afterwards - calling it multiple times will just make the random numbers not random, as you encountered.