登錄時產生驗證碼的問題。首先產生隨機數,然后讓產生的隨機數做為字符庫(提前做好的數字字母字符串)的下標,就這樣從字符庫中隨機提取出組成的小字符串就是最簡單的字符串了,當然你可以自己創建字符庫的內容。
以下是用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表。
歡迎碼友評論,我會不斷的修改使其變得完美,謝謝支持。