簡單的模擬取錢時輸入密碼:
#include<stdio.h>
#include<windows.h>
#include<string.h>
int main ()
{
int i=0;
int n=2;
char passwd[10];
char *p="123456";
for (i=0;i<3;i++)
{
printf("請輸入密碼:\n");
scanf("%s",passwd);
if (strcmp(p,passwd)==0)
{
break;
}
else
{
printf("密碼錯誤,請重新輸入!您還有%d次機會\n",n);
n--;
}
}
if (i<3)
{
printf("密碼正確!\n");
}
else if (i==3)
{
printf ("三次輸入錯誤,系統將在5秒鐘之後關閉!\n");
Sleep(5000);
exit(0);
}
return 0;
}
這裏要注意strcmp函數的使用,我在第一次寫的時候寫成了strcmp(*p,passwd),導致第一次輸錯密碼後程序崩潰;
函數簡介(來自百度)
原型:extern int strcmp(const char *s1,const char * s2);
所在頭文件:string.h
功能:比較字符串s1和s2。
一般形式:strcmp(字符串1,字符串2)
說明:
當s1<s2時,返回爲負數 注意不是-1
當s1==s2時,返回值= 0
當s1>s2時,返回正數 注意不是1
特別注意:strcmp(const char *s1,const char * s2)這裏面只能比較字符串,不能比較數字等其他形式的參數。
本文出自 “Original_By_Inn” 博客,轉載請與作者聯繫!