A Little C++ Game

I’m picking up C++ to add to the list of languages I’m familiar with. This is a little guessing game to start things in motion.

For those interested, I have attached the source code below. Do bear with me if something doesn’t seem optimal (and let me know what so I can improve!).

Things I’m proud of: Input error checking

Things I’m not so proud of: Infinite loops.

#include <iostream>
#include <cstdlib>
#include <string>
#include <time.h>

using namespace std;

int main () {
 int number, guess, yob, count, tries=0;
 string name;
 srand (time(NULL));
 
 number = rand() % 100 + 1;
 
 cout << "What is your name and year of birth (YYYY)?\n";
 while (!(cin >> name >> yob)) {
 cout << "You input wrong. Try again.\n";
 cin.clear();
 cin.ignore(1000, '\n'); 
 }
 
 cout << "Hello " << name << "! Let me guess, you are " << 2015-yob << " years old this year.\n";
 cout << "I'm right, ain't I?\n";
 cout << "Now it's your turn to guess!\n";
 cout << "I'm thinking of an number between 1 and 100\n";
 cout << "Can you guess it?\n";
 
 cout << "How many guesses do you think you need?\n";
 while (!(cin >> count)) {
 cout << "That's not a number! Try again. How many?\n";
 cin.clear();
 cin.ignore(1000,'\n');
 };
 
 cout << "Your guess: ";
 
 while(guess != number && tries != count) {
 if (!(cin >> guess)) {
 cout << "That's not a number! Try again.\n";
 cin.clear();
 cin.ignore(1000,'\n');
 }
 else if (guess > 100 || guess < 1) {
 cout << "Between 1 and 100 smartass! Try again.\n";
 }
 else if (guess > number) {
 cout << "That's too high, try again.\n";
 tries++;
 cout << "You have " << count-tries << "tries remaining.\n"; 
 }
 else if (guess < number) {
 cout << "That's too low, try again.\n";
 tries++;
 cout << "You have " << count-tries << " tries remaining.\n";
 }
 }
 
 if (tries==count) {
 cout << "You ran out of guesses.\nMy number is " << number << ".\n";
 }
 else
 cout << "You did it! My number is " << number <<"!\n";
 
 system("pause");
 return 0;
 
}

Leave a comment