-
My first program
Hi. I just started learning C++ last night. I've messed around a bit with just the cout and variable stuff, and today I've been trying to write a number guessing game. Here's what I have so far:
Code:
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
void main ()
{
int maxnum;
cout<<"\nHey, this is the Number Guessing Game Thing";
cout<<"Press control-C to close this program at any time.\n\n";
char plagain='y';
int right=0;
do
{
cout << "What number and 1 would you like to guess between?\n";
cin >> maxnum;
int guess;
cout<< "Ok, I'm now thinking of a number between 1 and " << maxnum << ". Try to guess it.\n";
const int LOW=1;
const int HIGH=maxnum;
int number;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
number=rand()%(HIGH-LOW+1)+LOW;
cin>>guess;
int right;
do
{
if(guess==number) {cout<<"You got it.";
cout << "\nWould you like to guess again? (y/n)\n"; cin>>plagain;
cout<<"\nOk. ";right==1;}
else if(guess>number) {cout<<"Too high. Guess again.\n";cin>>guess;right=0;}
else if(guess<number) {cout<<"Too low. Guess again.\n";cin>>guess;right=0;}
}while (right==0);
} while (plagain=='y');
}
It works fine except if you guess wrong ever, and then you get it right, when it asks you if you want to play again it says "Ok. You got it. Would you like to play again?" and then no matter what you type or whatever it just keeps saying that. What am I doing wrong?
-
Code:
cout<<"\nOk. ";right==1;}
// should be
cout<<"\nOk. ";right=1;}
And if you'd like to enjoy your stay here, never used void main() :D And this is just my opinion, but I think your format could use a bit of cleaning. Two statements on one line??
-
Ok, I did clean it up and used int main()/return 0. Thanks for your help!
-
You should change your header files to the standard ones.
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
Congratulations! Now you're conforming(sp?) to the ISO/ANSI C++.:cool:
-
You are actually running a infinite loop after you finish first processing of the input!:)