C++ program to generate CAPTCHA and verify user
A CAPTCHA is a test to check whether the user is a human or not. CAPTCHA verification is very widely used to determine the user is a human or machine. In this article, we will implement a program that generates a CAPTCHA and we will verify it in C++.
Examples
Input: CAPTCHA: x97s72s
user_input: x97s72s
Output: Valid CAPTCHA
Input: CAPTCHA: a67s89dP
user_input: a76s89dP
Output: Invaild CAPTCHAGenerate CAPTCHA in C++
We are using rand() to generate CAPTCHA randomly.
1. Create a function generateCaptcha that generate a CAPTCHA of length n
- Create an empty string captcha to store the generated captcha.
- use rand() function to add characters to the captcha.
2. Now get the user input.
3. Use compare() function to compare the generated captcha with user input.
#include <bits/stdc++.h>
using namespace std;
// function to check user input to generated CAPTCHA
bool check_Captcha(string &captcha, string &user_input){
return captcha.compare(user_input) == 0;
}
// function to generate CAPTCHA of length n
string generateCaptcha(int n){
time_t t;
srand((unsigned)time(&t));
char *required_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string captcha = "";
while(n--)
captcha.push_back(required_chars[rand()%62]);
return captcha;
}
int main(){
int n;
cout<<"Enter the required length of CAPTCHA: ";
cin>>n;
string captcha = generateCaptcha(n);
cout<<"CAPTCHA: "<<captcha<<endl;
string user_input;
cout<<"Enter the CAPTCHA: ";
cin>>user_input;
if (check_Captcha(captcha, user_input))
cout<<"Valid CAPTCHA"<<endl;
else
cout<<"Invalid CAPTCHA"<<endl;
return 0;
}Output
Enter the required length of CAPTCHA: 6 CAPTCHA: OsBVxh Enter the CAPTCHA: OsBVxh Valid CAPTCHA Enter the required length of CAPTCHA: 8 CAPTCHA: R5y3cVuW Enter the CAPTCHA: R5y3cVuW Valid CAPTCHA Enter the required length of CAPTCHA: 5 CAPTCHA: Y3EgK Enter the CAPTCHA: y3egk Invalid CAPTCHA
Also, read
Leave a Reply