www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/10/29/12:15:34

From: "Martin Lain" <LAINM AT feld DOT cvut DOT cz>
Organization: CVUT FEL student
To: djgpp AT delorie DOT com
Date: Thu, 29 Oct 1998 18:10:28 MET-1MEST
MIME-Version: 1.0
Subject: Re: Input problem
X-mailer: Pegasus Mail v3.40
Message-ID: <241CF782A11@FELIS.FELD.CVUT.CZ>
Reply-To: djgpp AT delorie DOT com

Hello,

well, I'm not using streams but I think you should better save the 
input into the string and then use a atoi() function. You can then 
catch out, if the user entered non-numbers.

Also, you should call srandom(&time()) (or somethink very like) to 
start the random number generator with random seed, or the numbers 
will be ever and ever the same.
And finally, the output of statement random()&100 is a number in 
range of 0-100! If you want numbers from 0 thru 99, use better 
random()%100.


> This program is a simple guessing game. You type in numbers and it says
> whether the number is higher or lower.
> 
> When I enter numbers, it is works fine.
> The problem is, when I type in a letter instead of a number the program goes
> pscho. From what I see on the screen, I think it is just going through my
> program without asking for further input.
> 
> Can you help me please?
> 
> Thanks in advance.
> 
> // Guessing Game
> 
> #include <stdlib.h>
> #include <time.h>
> #include <iostream.h>
> #include <conio.h>
> 
> main()
>  {
>   int r, guess, tries, playagain;
> 
>   clrscr();
> 
>   do
>    {
> 
> 
>     r = (random() & 100);
> 
>     cout << "Hello, this is a guessing game enter a number between 0-99:\n";
> 
>     for(tries=0; ;tries++)
>       {
>       cin >> guess;
>       if(guess > r) cout << "Too big\n";
>       if(guess < r) cout << "Too small\n";
> 
>       if(guess == r)
>         {
>         cout << "Yes you guessed right after "<< tries << "tries.\n";
>         break;
>         }
> 
>       if(tries > 15)
>         {
>         cout << "You are too dumb, you still can't get it after " << tries
> << " tries.\n";
>         cout << "The answer is " << r;
>         break;
>         }
> 
>       }
>    cout << "Do you want to play again?\n";
>    cin >> playagain;
> 
> 
>    } while(playagain);
> 
>    cout << "Bye!";
> 
>    getch();
> 
>    return 0;
> }
> 
> 
> 
> 
> 
> 

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019