Coders Packet

OTP generator using C++

By Vanshika Vaidya

Hello, In this tutorial, we will learn how to generate an OTP of a specific length in C++ with the help of the rand () and sleep () function.

The rand () function is defined in the stdlib.h.It is used to generate random numbers or strings of a specific length. We use this function when we want to generate random numbers.

The srand () function is defined in the stdlib.h .It sets the starting point for generating random integers. Whenever a different starting value is used in srand can generate different numbers as a result.

The sleep () causes the program to stop the execution temporarily for the given number of seconds.  

Creating an OTP generator using C++

OTP contains the alphabet, number, and special symbol. But we are using numbers only to generate OTP of a specific length. Length should be user define.

#include
#include
#include
#include
using namespace std;

string OTPgenerator(int n) // Generating OTP 
{

     string str = "0123456789";
     int len = str.length();
     string otp;
     int j;
     srand(time(0));
    for(int i=1;i<=n;i++)
    {
     int j = rand()%len;
     otp[i]=str[j];
    }
    for(int i=1;i<=n;i++)
    {
    	cout<<otp[i];
    }
    cout<<endl;
    cout<<"OTP will expire in 5 seconds....."<<endl;
    sleep(5);
    cout<<"Oops OTP is expired !!\n\n";
    int choice;
    cout<<"press 1 for new OTP generation"<<endl;
    cout<<"press 2 for exit \n\n";
    cin>>choice;
  
    switch(choice)
   {
    case 1: system("CLS");
            cout<<"New OTP : "<<OTPgenerator(n).c_str()<<endl;
            sleep(5);
            break;
    case 2: exit(0);
            break;
   }
}
int main() //main function 
{
  
   int n;
   cout<<"Enter length :";
   cin>>n;
   OTPgenerator(n);
   return 0;
}

 

Output:

Enter length:4
1740
OTP will expire in 5 seconds.....
Oops OTP is expired !!

press 1 for new OTP generation
press 2 for exit

1
8987
OTP will expire in 5 seconds.....
Oops OTP is expired !!

Thank you !!

 

Download project

Reviews Report

Submitted by Vanshika Vaidya (vaidya27)

Download packets of source code on Coders Packet