C ++程序生成验证码并验证用户

在本教程中,我们将讨论一个生成CAPTCHA并验证用户的程序。

为此,我们将为用户提供一个随机字符串,并要求他重新输入相同的字符串。然后,必须检查给定字符串和输入字符串是否匹配。

CAPTCHA应该是由az,AZ和0-9组成的完全随机的系统。

示例

#include<bits/stdc++.h>
using namespace std;
//检查字符串是否相同
bool check_string(string &captcha, string &user_captcha){
   return captcha.compare(user_captcha) == 0;
}
//生成一个随机字符串作为验证码
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;
}

输出结果

nwsraJhiP
Enter CAPTCHA :
CAPTCHA Not Matched