Pick a random card from a deck of cards in C++

In this tutorial, we will learn to write code to pick a random card from a deck of cards in c++

#include <iostream>
#include <cstdlib> //for rand and srand
#include <cstdio>
#include <string>
#include<ctime>//for accessing the time function
using namespace std;
string sign[] = { "Diamonds", "Hearts", "Spades", "Clubs" };
string value[] = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
        "Nine", "Ten", "Jack", "Queen", "King", "Ace" };

string randomcard() {
    string card;
    srand(time(0));//chnaging algorithms of rand() function with access of time
    int cardvalue = 1+(rand() % 13);//generating different values using rand ranging from 0to13
    int cardsign = 1+(rand() % 4);//generating different values from 0to4

    card += value[cardvalue];
    card += " of ";
    card += sign[cardsign];

    return card;
}

int main() {
    int numberofcards = 52;

   
        cout << "You drew a " << randomcard() << endl;
    

    
}

 

In this code we have used “cstdlib” (c standard library) and “ctime” (c time library) apart from the usual libraries. “cstlib” library has an in-built rand() function which is used to generate random numbers in the program.

Rand() function uses an algorithm to generate numbers but each time when we run code the same numbers are generated.

So srand() function is used to change the values generated by rand(). Srand() takes an integer value as input and for each integer value, a new number is generated by rand().

srand() is also an inbuilt function of “cstdlib” library. We have used the time() function to access the clock of the computer and it is given as an input to the srand() function.

The time() function is an in-built function of the “ctime” library which is used to access the clock of the computer. When it is passed to the srand() function it changes the value of the srand() input thus changing the values of the numbers given by rand() each time when we run the program.

Also read: Pick a random element from an array in C++

CODE EXPLANATION

1) In the code, first we included all the necessary libraries.

2) We define the two string arrays “sign” and “values”. They contain the total suits and total value of cards respectively.

3)After that we created a randomcard() function with a string return type.

4)In the function we are using srand() and rand() functions for creating unique values

5)After which elements from both the arrays are selected using those values and are passed in the main() function to display output.

OUTPUT

You drew a Seven of Clubs

In the output, we are getting a random card.

Leave a Reply

Your email address will not be published.