Question

Hi I'm working on an hangman project for my final in my c++ class. I've got most of it working but I wanted to make it so the player could have the option to play against a computer opponent in single player mode. I tried doing something like 97+rand()%123 so then convert the number to characters but I keep getting weird characters like an upside down f I checked to see if I was missing something but I have the right directives and I included a srand. a simplified version of what I did looks like this

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;

int main(){
    char cch;
    char ch; 
    unsigned seed= time(0)
    srand(seed)
    cch=97rand()%123;
    ch=cch;
    cout<<"computer chose "<< ch<<endl;
}

please note that I didn't include everything my project

Was it helpful?

Solution

Use

cch = 'a' + rand()%26;

This will add a random number to 'a' (which in int equals 97 but using that number makes your code less readable), remember 'a' == 97 because C and C++ don't actually care about your data type.

So if it is stored as char is will be seen as char

OTHER TIPS

You may find it easier to define a char array with all the valid characters you want to choose from, then pick a random character between 0 and the number of characters stored in the array;

char letters[] = "abcdefghijklmnopqrstuvwxyz";
char x = letters[rand() % 26];

It may not be as efficient, but it makes your intentions much clearer.

Also, if you ever needed to modify the probability of certain characters appearing more often, you could do so by adding the same character multiple times.

Take a look at ASCII table and note that valid characters are between 97 to 122 and 65 to 90. I think you need lowercase letters. You can choose a random lowercase letter like this:

char x = 97 + rand() % 26;

You don't want the computer to keep guessing the same letters over and over.

#include <random>
#include <iterator>
#include <iostream>
#include <algorithm>

int main() {
  char letters[] = { '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' };

  std::random_device r;
  std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
  std::shuffle(std::begin(letters), std::end(letters),
               std::mt19937(seed));

  for (char c : letters) {
    std::cout << "Computer chose: " << c << '\n';
  }
}

The formula should be : cch = 97 + rand()%26;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top