简体   繁体   中英

How can I stop C++ program?

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 need to fix up several things in your code:

  1. The variable c is kept uninitialized and incremented later to use nowhere. Remove this. Note that d , e , f are unused as well.

  2. 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; }
  3. 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";
  4. 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); } }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM