網站首頁 編程語言 正文
本文實例為大家分享了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
相關推薦
- 2022-07-21 shardingjdbc+mybatisP+Seata 報錯 throw new ShouldNev
- 2022-09-22 登錄、注冊相關業務邏輯(模擬登錄、注冊)-H5本地存儲
- 2022-08-05 Android自定義Span實現文字漸變效果_Android
- 2022-05-19 yolov5調用usb攝像頭及本地攝像頭的方法實例_python
- 2021-12-10 Golang?Gin框架實現文件下載功能的示例代碼_Golang
- 2022-05-16 C#中關于序列化與反序列化的三種方法_C#教程
- 2022-09-17 Golang文件讀寫操作詳情_Golang
- 2022-02-26 網頁小圖標和文字混排時如何對齊基準線
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支