Thread: the program generates a random number when its suposed to be a random letter

  1. #1
    Registered User
    Join Date
    Nov 2003

    Question the program generates a random number when its suposed to be a random letter

    The program compiles and executes fine but it generates a random number between 1-20 when i want it to generate a letter between c,d,h,and s.

    #include <iostream>
    #include <stdlib.h>
    #include <ctime>
    #include <cstdlib>
    #include <string>
    using namespace std;
    int main()
          char randsuit;
          const char suit[] = "cdhs";
          randsuit = suit[rand() % (sizeof(suit)-1)];
          cout << randsuit << endl;
          return 0;

  2. #2
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    You might need some more help on this hopefully someone else will help you out as well.

    As far as i understand it the sizeoff keyword will return the number of bytes in a given expression. so your code
    randsuit = suit[rand() % (sizeof(suit)-1)];
    is reading the size of the expression in that line. Not the actually elements of the array.

    What you might want to do is assign the letters c,d,h, s or whatever as individual elements of the suit array, ex: char suit = {"c", "d", "h", "s", "EXIT"} Not sure the actually code in C++, I'm still learning C so...

    Then your random function would be random() % 4 i think, whatever elements suits is, and you can designate what it should do when it returns a number in the length of suit ex: 1- 4.

    As it stands it seems that your the number of bytes in the expression with sizeof. Hope that helps a bit. I'm sure someone else can explain it better.
    Last edited by caroundw5h; 12-25-2003 at 12:04 AM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Code looks good - works pretty well too.

    The sizeof() is not the problem in this instance. On a char array, (sizeof(suit)-1) == strlen(suit)
    But it is evaluated at compile time not at run-time
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 02-08-2009, 09:26 PM
  2. non repeating random number generation?
    By gencor45 in forum C# Programming
    Replies: 1
    Last Post: 02-08-2005, 05:23 PM
  3. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  4. random number
    By mrukok in forum C++ Programming
    Replies: 7
    Last Post: 03-16-2003, 08:04 PM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM