hilo.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* $Source$
  2. * $State$
  3. * $Revision$
  4. */
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. char buffer[32];
  9. char PlayerName[32];
  10. int Number;
  11. int Attempts;
  12. void reads(void)
  13. {
  14. char* p;
  15. printf("> ");
  16. fflush(stdout);
  17. fgets(buffer, sizeof(buffer), stdin);
  18. p = strchr(buffer, '\n');
  19. if (p != NULL)
  20. *p = '\0';
  21. }
  22. void game(void)
  23. {
  24. printf("See if you can guess my number.\n");
  25. Number = rand() % 100;
  26. Attempts = 1;
  27. for (;;)
  28. {
  29. int guess;
  30. printf("\n");
  31. reads();
  32. guess = atoi(buffer);
  33. if (guess == Number)
  34. {
  35. printf("\nYou got it right in only %d %s!\n", Attempts,
  36. (Attempts == 1) ? "go" : "goes");
  37. return;
  38. }
  39. if (guess < Number)
  40. printf("\nTry a bit higher.\n");
  41. if (guess > Number)
  42. printf("\nTry a bit lower.\n");
  43. Attempts++;
  44. }
  45. }
  46. int main(int argc, char* argv[])
  47. {
  48. printf("\nHi there! I'm written in C. Before we start, what is your name?\n");
  49. reads();
  50. strcpy(PlayerName, buffer);
  51. printf("\nHello, %s! ", PlayerName);
  52. for (;;)
  53. {
  54. game();
  55. printf("\nWould you like another go?\n");
  56. reads();
  57. if ((buffer[0] == 'n') || (buffer[0] == 'N'))
  58. {
  59. printf("\nThanks for playing --- goodbye!\n");
  60. exit(0);
  61. }
  62. printf("\nExcellent! ");
  63. }
  64. return 0;
  65. }