Anyone got idea to do this?

”Guess the character”
Last edited on
Yeah... look up what the ascii numeric values for the characters are. Include <ctime> and seed srand() with the time so you can generate a number within that range

http://www.daniweb.com/software-development/cpp/threads/1769/c-random-numbers

Then you just compare the numeric value of the character the user entered to what was generated with srand() and tell the user whether she should guess a higher or lower letter.
You don't need the ASCII value or the array. Just the number in 0..25.

The character is num + 'A'. Make sure to std::toupper( users_char ) in order to compare it with the random character.

Hope this helps.
something wrong with my programme. anyone can help me with this?


Last edited on
Please use [code] tags. Like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
//#include <stdio.h>  // Don't use C I/O in C++ programs.
#include <stdlib.h>
#include <ctime>
using namespace std;


int main ()
{
  int i;
  char iSecret, iGuess;
//  char userInput;
//  int num;
//  char letters[27] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};  // unused
//  for(int i = 0; i < 26; i++)  // You already did this above...
//    letters[i+1] = 'a' + i;    // (it has a fencepost error here anyway)

  srand(time(NULL)); // Do this ONCE!

  iSecret = rand() % 26 + 'a'; // Watch the 'a'. Also do this only once. (It isn't fair to keep changing it in the game!)
    
  for(i=1; i<=10; i++)
  {
    cout << "Enter your guess for character:";
    cin >> iGuess;

//    scanf ("%d",&iGuess);  // Don't use scanf() or printf() in C++ programs.
cout << "(" << iGuess << " " << iSecret << ")\n";
    if (iSecret<iGuess)
    {
      cout << "Your guess is too high."<<endl;
    }
    else if (iSecret>iGuess)
    {
      cout << "Your guess is too low."<<endl;
    }
    
    // So what happens if I guess correctly?
    // (You should break out of the loop.)
    else break;
  }

  if
  (iSecret==iGuess) //; <-- no semicolon here!
  {

    cout << "You're right! You win!" <<endl;
  }
  else // Say something if player loses too
  {
    cout << "Aww, too bad. The letter I was looking for was '" << iSecret << "'.\n";
  }

  system("pause");
  return 0;
}

If you must use the letters array, then generate a secret as an index into the array:

1
2
3
int secret;

secret = rand() % 26;

And use it:

1
2
3
4
if (guess < letters[ secret ])
{
   ...
}

Hope this helps.
Topic archived. No new replies allowed.