我们很多上网输入密码的时候会有需要输入验证码的过程,那我就做个简单的验证码系统。
首先,我们需要包含一些必要的头文件
#include <stdio.h> // 标准输入输出库
#include <string.h> // 字符串处理库
#include <stdlib.h> // 标准库,包含rand()和srand()
#include <time.h> // 时间库,用于生成随机数种子
1. 初始化随机数生成器
为了生成随机的验证码,我们需要初始化随机数生成器:
srand(time(NULL)); // 使用当前时间作为种子
2. 定义全局变量
定义一些全局变量,和用于存储验证码的字符串和用户输入的字符串:
int count = 0; // 错误次数计数器
char str[65] = "1230456789qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP"; // 可能的字符集
3. 生成验证码
在无限循环中,我们生成一个四位的验证码:
char yanz[5] = {0}; // 存储验证码
char input[100] = {0}; // 存储用户输入
for (int i = 0; i < 4; i++)
{
int j = rand() % 62; // 从字符集中随机选择一个字符
yanz[i] = str[j];
}
4. 输出验证码并获取用户输入
输出生成的验证码,并提示用户输入:
printf("你的验证码为:%s\n", yanz);
printf("请输入验证码:");
scanf("%s", input);
5. 验证用户输入
比较用户输入的验证码和程序生成的验证码,如果不一致,增加错误次数:
if (strcmp(yanz, input) != 0)
{
count++;
}
else
{
printf("验证成功!\n");
break;
}
6. 错误处理
如果用户连续三次输入错误,程序将输出错误信息并终止:
if (count >= 3) {
printf("错误次数太多!\n");
break;
}
printf("验证错误,请重新输入!\n");
7. 以下是整个代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int count=0;
int i;
char str[65] = "1230456789qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP";
while(1){
char yanz[5]={0};
char input[100]={0};
int j=0;
for(i=0;i<4; i++)
{
j=rand()%62;
yanz[i]=str[j];
}
printf("你的验证码为:%s\n",yanz);
printf("请输入验证码:");
scanf("%s",input);
if (strcmp(yanz,input)!=0)
{
count++;
}
else
{
printf("验证成功!\n");
break;
}
if (count>=3)
{
printf("错误次数太多!\n");
break;
}
printf("验证错误,请重新输入!\n");
}
return 0;
}

770

被折叠的 条评论
为什么被折叠?



