Old School C++ guess the number game

It's been a while since I blogged but I've got some old fashioned code I've updated using the latest versions. This is some C++ code for a simple guessing game. You get 10 tries to guess a number between 1 and 100. The game picks the number randomly and tells you if you've guessed to low, to high, or correctly. This is written using the newer C++ 11 standard so you'll notice some weird stuff with the random number generating. I will post some links to this below.
 #include <iostream>  
 #include <random>  

 using namespace std;  

 int main()  
 {  
      random_device randomDevice;  
      mt19937 mt(randomDevice());  
      uniform_real_distribution<double> dist(1.0, 100.0);  
      
      int numberOfTries = 0;  
      int numberToGuess = dist(mt);  
      int maxNumberOfTries = 10;  
      int currentGuess = 0;  
      
      bool wonGame = false;  
      
      cout << "Welcome to guess the number" << endl << endl  
           << "Your goal is to guess the number between 1 and 100 in 10 tries or less" << endl << endl;  

      do  
      {  
           cout << endl << "Guess(" << numberOfTries + 1 << "): ";  
           cin >> currentGuess;  
           if (!cin.fail() && currentGuess > 0 && currentGuess <= 100 )  
           {  
                if (currentGuess == numberToGuess)  
                {  
                     wonGame = true;  
                     break;  
                }  
                else   
                {  
                     if (currentGuess > numberToGuess)  
                     {  
                          cout << "Too High" << endl;  
                     }  
                     else  
                     {  
                          cout << "Too Low" << endl;  
                     }  
                     numberOfTries++;  
                }  
           }  
           else  
           {  
                cin.clear();  
                cin.ignore();  
                cout << "Invalid guess" << endl;  
                continue;  
           }  
      } while (numberOfTries < maxNumberOfTries);  

      if (wonGame)  
      {  
           cout << endl << "Congratulations you guessed the secret number: " << numberToGuess << " in " << numberOfTries << " tries." << endl;  
      }  
      else  
      {  
           cout << endl << "Sorry you didn't guess the secret number: " << numberToGuess << " in 10 tries or less." << endl;  
      }  
 }  

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Producer Consumer using Rabbit MQ

C# Form Application in Kiosk Mode/Fullscreen