簡體   English   中英

如何限制輸入的字符數

[英]How to limit the amount of characters entered

因此,我正在研究一個簡單的密碼程序。 到目前為止,我已經有了此代碼

/* simple  password prog */
#include<stdio.h>
#include<string.h>
int main(){
        char usrIn[9];
        char password[]={"AXcd8002"};
        do {

        fprintf(stdout,"\n Password:");
        fgets(usrIn,9, stdin);
        if  ( strcmp(usrIn,password)<0 || strcmp(usrIn,password )>0 ) { 
        fprintf(stdout,"\n Password incorrect"); };

        }while( (strcmp(password,usrIn))!=0 );

fprintf(stdout, "\n The password is correct \n");
return 0;
}

此代碼正確運行,如果密碼不正確,則循環將繼續進行;如果正確,則循環將中斷。 但是這是行不通的:如果用戶輸入的密碼至少包含一個字符,則程序仍然會說正確。 例如,如果用戶輸入AXcd8002AAA,則fgets將僅讀取AXcd8002,而忽略AAA。 如何防止這種情況發生?

usrIn只有9個字符,當然多余的字符將被忽略。 只要給usrIn足夠的空間即可:

char usrIn[100];

並作為最佳實踐:

fgets(usrIn, sizeof(usrIn), stdin);

還有一個您沒有考慮的問題: fgets將換行符'\\n'視為有效字符,因此它也在usrIn ,您需要在比較密碼之前手動將其刪除。

如果不提供usrIn的大小,則不提供動態大小並執行動態輸入,會將完整密碼插入數組usrIn中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM