C++ program to generate CAPTCHA and verify user


In this tutorial, we will be discussing a program to generate CAPTCHA and verify user.

For this, we will provide the user with a random string and ask him to reenter the same string. Then it has to be checked if the given and the input string matches.

The CAPTCHA should be completely random system generated consisting of a-z, AZ and 0-9.

Example

#include<bits/stdc++.h>
using namespace std;
//checks if the strings are same
bool check_string(string &captcha, string &user_captcha){
   return captcha.compare(user_captcha) == 0;
}
//generates a random string as Captcha
string gen_captcha(int n){
   time_t t;
   srand((unsigned)time(&t));
   char *chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHI" "JKLMNOPQRSTUVWXYZ0123456789";
   string captcha = "";
   while (n--)
      captcha.push_back(chrs[rand()%62]);
   return captcha;
}
int main(){
   string captcha = gen_captcha(9);
   cout << captcha;
   string usr_captcha;
   cout << "\nEnter CAPTCHA : ";
   usr_captcha = "fgyeugs56";
   if (check_string(captcha, usr_captcha))
      printf("\nCAPTCHA Matched");
   else
      printf("\nCAPTCHA Not Matched");
   return 0;
}

Output

nwsraJhiP
Enter CAPTCHA :
CAPTCHA Not Matched

Updated on: 03-Dec-2019

604 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements