Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help looping my program?

Status
Not open for further replies.

DocHaydn

Programmer
Feb 24, 2004
12
CA
Hello,
I'm a learner; running Win'98SE, compiler:minGW dev. studio.

The following is a simple "guess the number" game.

It compiles, and runs without erors. However, I
don't know how to loop it back to play again, if
the user enters (y) yes. How do I do this?

I've tried removing the do-while, and replacing
it with a: while(1){, and a flag = 0;, flag = 1;,
but no joy.

At present, I'm learning how to use the "function's
return value." Since this is my first go at it, I
don't know if I'm doing it correctly; as the program
does not loop, but exits with "press any key to continue."

All help would be greatly appreciated. Here's what I've
done so far.

Thank you.

Code:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>

int game(void)
{
   int usenum, rannum, count;
   srand(time (NULL));
   rannum = rand()%10;
   count = 0;

   do
   {
      printf("Guess the number.\n");
      scanf("%d", &usenum);
      getchar();
	 count++;

      if(usenum == rannum)
      {
		 printf("Congratulations!It took you only %d guess/guesses.\n", count);
         break;
      }
		 
      if(usenum < rannum)
      {
         printf("Too low... try again.\n");
      }
      else
      {
         printf("Too high... try again.\n");
      }
    } while(usenum != rannum);

      printf("Would you like to play again? (y/n):");
	  fflush(stdout);
    
	  return tolower(getchar()) == 'Y';
 
}
int main(void)
{
   while(game());

   return 0;
}
 
> return tolower(getchar()) == 'Y';
You make the character lower case, then compare it with the upper case.

This can never be true.

--
 
Try this, change the code to as follows:

Code:
...
      return tolower(getchar());
 
}
int main(void)
{
   while(game() == 'y');

   return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top