CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2009
    Posts
    1

    number guessing game

    i am new to c++ but i know some other languages. I have been programming in c++ for about 5 hrs now and i am having a problem with my program. when i guess for the first time it is like it doesn't count. no matter what i type it will tell me that my guess is too low. can anyone help me?

    #include <cstdlib>
    #include <iostream>
    #include <ctime>

    using namespace std;

    int main()
    {
    long guess = 0, x = 0;
    const long MAX = 500, MIN = 1;

    srand(time(NULL));
    x = (rand() % (MAX - MIN + 1)) + MIN;

    while (guess != x)
    {
    cout<< endl;
    cout<<"Enter a number between 1 and 500" << endl;
    cin.ignore();
    cin>> guess;
    cout<<"The secret number is " << x;
    if (guess < x) {
    cout<<"You was too low, Try again"; }
    else if ( guess > x) {
    cout<<"You was too high, Try again";}
    else {
    cout<<"Invalid guess";}
    }
    }

  2. #2
    Join Date
    May 2002
    Posts
    1,435

    Re: number guessing game

    What is the purpose of cin.ignore()? That is probably what is wrong with your code. Try removing it and see what happens.

    Also try printing out the guess:

    Code:
    	if (guess < x){
    		cout << "Your guess (" << guess << ") was too low, Try again" << endl; }
    	
    	else if ( guess > x){
    		cout << "Your guess (" << guess << ") was too high, Try again" << endl; }
    
    	else{
    		cout << "Invalid guess (" << guess << ")" << endl; }
    }
    Last edited by 0xC0000005; August 15th, 2009 at 07:40 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured