Wednesday, 9 January 2013

Code Challenge: "Guess That Number!"

I discovered the sub Reddit dailyprogrammer which post up different programming challenges for people to solve, so for a bit of fun when i have the time i am going to pick some of the challenges and give them a go and then i will stick my code up here for any one that is interested and to hopefully get some feedback as well.

The first challenge i have chosen is Challenge #115 [Easy] Guess-That-Number game which i have attempted to do in C++.

The aim of the challenge was to write a program which guessed a number between 1 and 100 and then ask the user to guess what that number was and then either tell them if their guess is too high, too low or correct. or exit if the user enters "Exit". Here is my code.


I am not entirely sure if this is the best way to do it but what i have done is this. I read in the users guess, try and convert the input into an integer, if it is successful i check if the number is equal to, higher than, lower than or out of range and then return a string value based upon what it is and then display this string value to the user. If the conversion fails i check to see if the user has entered the string "Exit" and if they have i break; and end the program. Any other input i display an error message. This continues on until the user guesses the correct value at which point the loop is exited and the program terminates. 

You can find and download the code from my git hub account here, feel free to use the code as you wish and if you make any improvements please let me know, i would love to hear from you. 

No comments:

Post a Comment