日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言實現簡單登錄操作_C 語言

作者:今天也要寫bug、 ? 更新時間: 2022-08-06 編程語言

本文實例為大家分享了C語言實現簡單登錄的具體代碼,供大家參考,具體內容如下

編寫代碼實現,模擬用戶登錄情景,并且只能登錄三次。

要實現這種操作,我們需要設置一個字符串arr1用來存放密碼,同時還要手動輸入一個字符串password來記錄我們輸入的字符串,并將password與arr1字符串比較判斷是否相同。同時for循環三次即可,如果輸入正確則跳出循環。

值得注意的是: 在比較password與arr1是否相等時,不能夠用==比較,比如下面的程序:

#include <stdio.h>
int main()
{
?? ?char password[10] = "";
?? ?char arr1[] = "123456";
?? ?int i = 0;
?? ?int j = 0;
?? ?for (i = 0; i < 3; ++i)
?? ?{
?? ??? ?printf("請輸入密碼:");
?? ??? ?scanf("%s", password);
?? ??? ?if (password==arr1)//使用等號比較字符串 錯誤
?? ??? ?{
?? ??? ??? ?break;
?? ??? ?}
?? ??? ?else
?? ??? ?{
?? ??? ??? ?printf("密碼錯誤,請重新輸入\n");
?? ??? ?}
?? ?}
?? ?if (i == 3)
?? ??? ?printf("輸入次數用完\n");
?? ?else
?? ??? ?printf("登陸成功\n");
}

使用==比較字符串相等是不行的,因為字符串password的本質是一個字符數組,password只是數組名,而在數組那一章我們知道數組名代表的是數組首元素地址(sizeof和直接&除外),所以password==arr1比較的實際上是這兩個字符數組首元素的地址,很明顯這倆地址是不相同的,因此不能用 == 比較字符串是否相等。

在C語言<string.h>頭文件中有個strcmp的庫函數:

因此我們可以使用這個庫函數來比較他倆是否相等,如果相等則返回0,否則則返回非0.
修改后的代碼:

#include <stdio.h>
#include<string.h>
int main()
{
?? ?char password[10] = "";
?? ?char arr1[] = "123456";
?? ?int i = 0;
?? ?int j = 0;
?? ?for (i = 0; i < 3; ++i)
?? ?{
?? ??? ?printf("請輸入密碼:");
?? ??? ?scanf("%s", password);
?? ??? ?if (strcmp(password, arr1) == 0)
?? ??? ?{
?? ??? ??? ?break;
?? ??? ?}
?? ??? ?else
?? ??? ?{
?? ??? ??? ?printf("密碼錯誤,請重新輸入\n");
?? ??? ?}
?? ?}
?? ?if (i == 3)
?? ??? ?printf("輸入次數用完\n");
?? ?else
?? ??? ?printf("登陸成功\n");
}

原文鏈接:https://blog.csdn.net/qq_52670477/article/details/118633605

欄目分類
最近更新