登录时产生验证码的问题。首先产生随机数,然后让产生的随机数做为字符库(提前做好的数字字母字符串)的下标,就这样从字符库中随机提取出组成的小字符串就是最简单的字符串了,当然你可以自己创建字符库的内容。
以下是用C语言编写产生验证码和验证验证码的过程的代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 #include <string.h> 5 #define N 5 6 7 void identifying_Code (char str[],int n) { 8 int i,j,len; 9 char pstr[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ"; 10 len = strlen(pstr); //求字符串pstr的长度 11 srand(time(0)); 12 for (i = 0;i < n; i++) { 13 j = rand()%len; //生成0~len-1的随机数 14 str[i] = pstr[j]; 15 } 16 str[i] = '\0'; 17 } 18 19 int main() { 20 int n = 3; 21 int flag = 0; 22 char code[N+1],str[N+1]; 23 while (n) { 24 identifying_Code (code,N); 25 printf("请输入验证码<您还剩%d机会>:%s\n",n,code); 26 scanf("%s",str); 27 n--; 28 if(strcmp(code,str) == 0) { //区分大小写的验证码 29 n = 0; 30 flag = 1; 31 printf("验证正确.\n"); 32 } 33 } 34 if (flag == 0) 35 printf("对不起,您的账号已锁定.\n"); 36 return 0; 37 }
还有一种直接调用库函数的,比上面的写的代码还简单点,有兴趣的码友可以参考一下。
1 #include <cstdio> 2 #include <ctime> 3 #include <iostream> 4 #include <algorithm> 5 #include <cstring> 6 using namespace std; 7 int main () { 8 int m, n; 9 srand (time (NULL));//初始化 10 n = rand() % 100; //生成两位数的随机数 11 cout << n << endl; 12 return 0; 13 }
rand()函数需要的C语言头文件为 stdlib.h, c++的为 algorithm,当然也可以写cstdlib。它不需要参数就可以产生随机数。这里可以产生字母的,就是根据ASCII表。
欢迎码友评论,我会不断的修改使其变得完美,谢谢支持。