Guessing game code

How's my coding? I am trying to build a guessing game that's between 1-20 in 3 guesses or less.


#include <stdio.h>
#include <time.h>

int main(void)
{
int Guesses = 5;
int Guess;
int Answer;

srand(time(NULL));
Answer = rand() % 20 + 1;

cout << " Welcome to the Guessing Game! \n";
cout << "I'm thinking of a certain number between 1 and 20, what is it?" << Guesses << "tries?\n";

for (int i = 0; i < Guesses; i++)
{
cout << "Guess #" << i+1 << ": ";
cin >> Guess;

if (Guess != Answer)
{
if(Guess > Answer)
cout << "to high.\n";
else
cout << "to low.\n";
}
else
{
cout << "you won!\n";
system("pause");
return 0;
}
}

cout << "you lost!\n";
cout << "The correct answer was :" << Answer << endl;
system("pause");
return 0;
}

Last edited on
These headers tell me the code is written in the C language:
1
2
#include <stdio.h>
#include <time.h> 


but the use of cin and cout indicates it must be C++. So replace those two lines with the C++ headers:
1
2
3
#include <iostream>
#include <cstdlib>
#include <ctime> 


You also need to specify the namespace, by putting the prefix std:: where required, such as
std::cout and std::cin or for now just add
 
using namespace std;
at the top of the program, after the headers.
It is common practice not to include void between the parentheses of int main. Just leave it empty.
int main()

And when you say to high or to low. I believe it should be "too"

To me it doesn't seem that the statements
1
2
cout << "you lost!\n";
cout << "The correct answer was:" << Answer << endl;
is nested in anything. Meaning it will always output these statements no matter what.

Those same statements could be made into one cout statement cout << "you lost!\nThe correct answer was :" << Answer << endl;(This also goes for lines 13 and 14)
Last edited on
Topic archived. No new replies allowed.