How can I stop C++ program? - c++

I made a program that prompts the user to guess numbers (which I have programmed to produce a random number)ranging from 1-10, if the user guesses the number successfully which is the same as the random number generated it prints "congratulation", else it prompts the user to try again. but I want to stop the user from answering after a certain amount of time(like Game Over). But the prompt keeps coming, I tried using the break in my while loop but it doesn't work, I also tried using the exit function, which actually stopped the program from running but it stopped it after answering 2 times which is not what I want.
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
int a,b,c,d,e,f;
// generate a random number, prompt the user for any number if the users guess is in line with the random number generated the user wins else try again
//generate a random number between 1 - 10 store it in a variable
cout << "Random Number Generator \n \n";
srand(time(0));
for(int i = 1; i == 1; i++){
a = 1+(rand() % 10);
cout << a << endl;
}
//prompt the user for numbers ranging from 1 - 10
cout << "type in a number from (1 - 10)\n";
cin >> b;
c++;
//check if the number is the same as the random number
//this checks to see if the user gets the question, else it continues running till he gets it
while(a != b){
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
while(b <= 3){
exit(3);
}
}
//print result
if(a == b){
cout << "congratulations";
}
return 0;
}
how can I make this work?

You could count the number of times the user answers and stop when it has executed for the number of times you want.
//prompt the user for numbers ranging from 1 - 10
cout << "type in a number from (1 - 10)\n";
cin >> b;
int answer_count = 1; // variable to count answers (there is already 1 answer here)
const int max_attempts = 10; // number of attempts the user has
//check if the number is the same has the random number
//this checks to see if the user gets the question, else it continues running till he gets it
while(a != b){
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
answer_count++; // count this new answer
if (answer_count >= max_attempts){ // check if the count reached the "certain amount of time"
break; // exit from this loop
}
}
Alternatively, you could also give the user a certain amount of time to guess. For example, 10 seconds. This can easily be achieved using the C++ chrono library:
#include <chrono>
#include <iostream>
#include <random>
int main(int argc, char **argv)
{
const int max_time = 10; // seconds
const int min_secret = 1;
const int max_secret = 10;
// This generates a random number between min_secret and max_secret using the STL random library
std::random_device r;
std::default_random_engine e(r());
std::uniform_int_distribution<int> uniform_dist(min_secret, max_secret);
int secret = uniform_dist(e);
auto start = std::chrono::system_clock::now();
int guess;
do {
std::cout << "Type a number from (1 - 10)\n";
std::cin >> guess;
if (guess == secret)
break;
std::cout << "Your guess is incorrect!\n";
// See if the time elapsed since the start is within max_time
auto now = std::chrono::system_clock::now();
auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(now - start);
if (elapsed_time.count() > max_time) {
std::cout << "You ran out of time.\n";
exit(0);
} else {
std::cout << "You still have " << max_time - elapsed_time.count() << " seconds left\n";
}
} while (guess != secret);
std::cout << "Your guess was correct, congratulations!";
}
Note that the time check is only performed after the user tried to guess, so if the time limit is 10 seconds and the user waits 30 to type, it will still allow. To kill the program entirely with a timer in C++, you could use the thread library to spawn a second thread that handles the elapsed time, or even use an interruption based scheme (see https://stackoverflow.com/a/4001261/15284149 for an example of timer).
Also, note that the user input is not sanitized, and if the user writes anything other than a number your program has undefined behavior.

You need to fix up several things in your code:
The variable c is kept uninitialized and incremented later to use nowhere. Remove this. Note that d, e, f are unused as well.
In the loop:
for(int i = 1; i == 1; i++) {
a = 1 + (rand() % 10);
cout << a << endl;
}
You have told the compiler to iterate until i == 1, increment it by one, it is only done once – and that you might not want to do but i < 10.
Also, You are not using an array to store those 10 random numbers, but the last one. You need to make an array of 10 rooms and assign it to each of them:
int a[10];
// Since the array index begins at zero
for (int i = 0; i < 10; i++) {
a[i] = (rand() % 10) + 1;
cout << a[i] << endl;
}
After the successful assignment, it's time to introduce a randomly chosen index as the right answer (it should be put before the while loop):
// To choose the random index
int shuffle = a[rand() % 10];
Also, replace the congratulating statement:
// It was a == b previously
if (shuffle == b)
cout << "congratulations";
Lastly, to quit after three incorrect attempts, replace the while loop:
int count = 0;
while (shuffle != b) {
count++;
cout << "You're incorrect!\n";
cout << "type in a number from (1 - 10)\n";
cin >> b;
if (count == 2) {
cout << "Game Over" << endl;
exit(0);
}
}

Related

Issues with rand and srand

I'm making a program to get the average number of dice rolls to get a 6, but there seems to be an issue with the RNG. I suspect it's the seed, as while the number is different each time I compile and run the code, it doesn't change in each individual attempt, so the average doesn't change. Heres my code:
#include <iostream>
#include <cstdlib> // random numbers header file//
#include <ctime> // used to get date and time information
using namespace std;
int main()
{
int roll = 0; //declare a variable to keep store the random number
int i = 0;
int counter = 0;
int resume = 1;
int average = 0;
int totalrolls = 0;
srand(time(0)); //initialise random num generator using time
while (resume != 0) {
while (roll != 6) {
roll = rand() % 6 + 1; // generate a random number between 1 and 6
i++;
}
counter++;
totalrolls += i;
average = totalrolls / counter;
cout << "the average number of rolls to get a 6 is " << average << ", based on " << counter << " sixes." << endl;
cout << "do you wish to keep rolling? ";
cin >> resume;
cout << endl;
}
return 0;
}
Anyone got any idea what's going on?
Notice that roll only gets updated inside this loop:
while (roll != 6) {
...
}
This means that after that loop finishes running with roll set to 6, it will never run again, even if the outer loop executes another time.
To fix this, you could either
change this to be a do ... while loop so that it always executes at least once; or
manually reset roll to a value other than 6 on each iteration through the outer while loop; or
change where roll is defined so that it's local to the outer while loop and so you get a fresh copy of it per outer loop iteration, which is basically a better version of option (2).

My loop won't loop

I have an assignment where we have to write code that finds a number that fits four parameters. My idea was to split up that number into its individual digits, then have an if statement that checks if the number fits the parameters. If it doesn't I wanted it to increase by one and loop until it finds the number. My loop only runs once however, and doesn't even return all four digits. Any direction on what I should do would be appreciated.
#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{
int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number
do{
number++;
last_dig = number%10; //This series of code breaks up the number into digits
number /= 10;
third_dig = number%10;
number /= 10;
sec_dig = number%10;
number /= 10;
first_dig = number%10;
number /=10;
if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last$
number = secret_number;
}while((secret_number = 0));
cout << "You found the secret number! That number is " << secret_number;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;
}
I have changed the logic and few statements as per the problematic statement given. Even though you will change the while loop condition as suggested, you will not get exact output.
So the changes are.
A) secret_number assigned at the beginning of the loop and holds the incremented number
B) do the modification operations on secret_number variable
C) use "break" once the condition is met.(because you got your secret number)
E) Because your condition is endless till you find a required number changed the loop to while(1) [This is optional you can set it to some upper limit]
F) Display the number itself.
Below is the code details.
#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{
int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number
do{
secret_number = ++number;
last_dig = secret_number%10; //This series of code breaks up the number into digits
secret_number /= 10;
third_dig = secret_number%10;
secret_number /= 10;
sec_dig = secret_number%10;
secret_number /= 10;
first_dig = secret_number%10;
secret_number /=10;
if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last_dig)){
break;
}
}while(1); //To avoid endless loop you can set some upper_limit
cout << "You found the secret number! That number is " << number<<endl;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;
return 0;
}
Output is as follows:
/WorkDir/checks/stackover> vi loop_digit.cpp
/WorkDir/checks/stackover> g++ -Wall -Wextra -O2 -o loop_digit loop_digit.cpp
/WorkDir/checks/stackover> ./loop_digit
You found the secret number! That number is 1022
2
2
0
1
Change
while((secret_number = 0));
to
while(secret_number == 0);
Single = is an assignment operator, for comparison you need ==
There's also a $ sign in one of the conditions of if-statement inside while loop that you might want to rectify.

multiplication game loop slide issue

So I am determined to make an epic math console based game for fun.
I am curious as to why when the random enters a zero, the program slides through a series of multiplied by 0 and skips the "please enter: " portion of my code.. Is this because of the true and false boolean features of the test condition in the while loop? More importantly how can I stop this from happening?
Thank you for all of your help!
// multiplicationgame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void game();
int _tmain(int argc, _TCHAR* argv[])
{
// waiting.cpp : Defines the entry point for the console application.
//
cout << "Welcome to Math game!\n\n" << endl;
float secs;
secs = 3;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
while (clock() - start < delay )
;
char choice = 'z';
game();
while(choice != 'n')
{
cin >> choice;
if (choice == 'y')
{
cout << "\n\n";
game();
}
else
choice = 'n';
}
return 0;
}
void game()
{
float secs;
secs = 33;
clock_t delay = secs * CLOCKS_PER_SEC;
clock_t start = clock();
int correct = 0;
while (clock() - start < delay )
{
srand(time(NULL));
int a = rand() % 23;
int b = rand() % 23;
int c = (a * b);
int d = 0;
char choice = 0;
cout <<"What does " << a << " * " << b << " equal?" << endl << endl << endl;
cout << "\n";
while(d != c)
{
cout << "Please enter a number: ";
cin >> d;
if(d == c)
++correct;
}
cout << "\n\nCorrect! " << (a * b) << " is the answer!" << endl << endl;
}
cout << "Your score is: " << correct << "\n\n" <<endl;
cout << "Would you like to play again (Y) or (N)?\n\n\n";
}
You assume the answer is wrong if c is not equal to d, but if a or b are set to zero , c and d are equal before your user can ever enter a number. One solution would be to use a do { ... } while ( ... ); loop instead of a while loop to ensure the user is always asked for a number before your test for the correct answer is performed.
As Markku said, don't set d = 0, because if either a or b is equal 0, then c = a * b = 0 and then your while loop condition c != d won't hold and so it will be skipped
You initialize d to be 0, and anything times 0 is 0. Thus the (d != c) condition will always be false, and you don't enter the while(d!=c) loop.
You are getting 0 several times, because the while loop finishes very quickly, and so when you call srand(time(NULL)), time(NULL) will return the same value as the previous itteration, and you get the same random seed (which gets you 0 again).
initialize d to be -1 (or some other value that a*b can't be). Move the srand outside of your while loop -- you only have to (and only should) call srand once in your program.
John
Quick fix: initialize int d = -1; instead of int d = 0;.
You're initializing int c = a * b. Since either a or b is zero, the multiplication results in c being zero. You also initialize int d = 0;. Then you have while(d != c), but you assigned both of them to zero, hence your program skips over that loop because d != c is false.
#AEGIS No, the srand(time(NULL)) merely seeds the random number generator with a somewhat random value based on the current time whenever the program is run. This ensures that each run of the program will produce a different set of multiplication problems to solve.
#AEGIS The outer while (clock() - start < delay ) { ... } loop terminates when the "delay" time has expired. The inner while(d != c) { ... } loop is never entered at all when a or b are zero, or loops forever as long as the user enters wrong answers. So though it is not a real problem in practice -- any user is likely to finally get the correct answer or abort the program manually -- this is a program which is not certain to ever terminate.
#Ned Nowonty looking at the screen shot AEGIS provided the outer loop didn't terminate. If it did then the
Your score is: (some number)
Would you like to play again (Y) or (N)?
would have appeared. When you srand with the same initializer you end up with the same pseudo random numbers. So when one of the variables was initialized to 0 it would loop around until time(NULL) provided srand a different variable. In order to avoid that you could use an iterator as well as the time function so the seed would be different all the time.

Is this C++ Guessing Game syntactically correct?

#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
int guess = 0;
cout << "What is your guess? " << endl;
cin >> guess;
if(guess < randomint){
cout << "Too low!" << endl;
count++;
} else if (guess > randomint){
cout << "Too high!" << endl;
count++;
} else{
cout << "Correct!" << endl;
cout << "Number of Guesses: " << count << endl;
isCorrect = true;
}
}
}
New C++ Programming. I couldn't get this to compile one IDEOne because it doesn't have the input system I need to work this program. I have to submit this for a class shortly, but given that my larger disk (where all my software was stored) was corrupted last night.
I apologize for the silliness of this question.
Yes, it is syntactically correct, but not logically, due to
bool isCorrect = true;
which prevents loop from starting, it should be
bool isCorrect = false;
and works like a charm (but it would be reasonable to initialize the random number generator by for example running srand(time(NULL));)
There are two things logically wrong in your program:
The game won't run at all, since isCorrect is initially true.
The random number generator doesn't get a seed, so rand() will return the same value on every run and randomint is always the same. You should call srand( seed ) beforehand, where seed is a unsigned (for example time(0)).*
*actually, your game will still run if you don't do this, but it's easy to beat after the first try

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!