簡體   English   中英

C-限制字符串長度

[英]C - Limit the string length

(對不起,我的英語不好 !)

我寫了一個程序,要求您輸入密碼,密碼不能超過一個特定的數字,在這種情況下為八個字符。 超過限制的字符將從數組中切出:

#include <stdio.h>
#define MAXCHAR 8

main()
{
    char password[MAXCHAR];
    int i;
    char c;

    printf("Insert password: MAX 8 CHARS!\n\n");
    for(i = 0; i <= MAXCHAR; i++){
        c = getchar();

        if(i == MAXCHAR){
            break;
        }
        else{
            password[i] = c;
        }
    }

    printf("%s\n", password);
}

因此該程序可以運行,但是存在“奇怪”問題。 如果限制為EIGHT,並且我輸入的密碼長於八個字符(例如:P455w0rds98),則輸出將如下所示:

P455w0rd☺

所以結尾處帶有笑臉,我不知道為什么。 僅當將限制設置為8時才會發生。

您必須指定打印或終止字符串的長度。 否則,您將調用未定義的行為 嘗試執行后一種方法。

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
    char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
    int i;
    char c;

    printf("Insert password: MAX 8 CHARS!\n\n");
    for(i = 0; i <= MAXCHAR; i++){
        c = getchar();

        if(i == MAXCHAR){
            break;
        }
        else{
            password[i] = c;
        }
    }
    password[MAXCHAR] = '\0'; /* terminate the string */

    printf("%s\n", password);
}

有人說if(i == MAXCHAR){ break; } if(i == MAXCHAR){ break; }部分看起來不太好,所以這是另一個代碼示例:

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
    char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
    int i;

    printf("Insert password: MAX 8 CHARS!\n\n");
    /* read exactly 8 characters. To improve, breaking on seeing newline or EOF may be good */
    for(i = 0; i < MAXCHAR; i++){
        password[i] = getchar();
    }
    password[MAXCHAR] = '\0'; /* terminate the string */
    getchar(); /* to match number of call of getchar() to the original: maybe for consuming newline character after 8-digit password */

    printf("%s\n", password);
}

除了您已經從MikeCAT收到的答案之外 ,另一種方法是利用fgets()讀取用戶輸入。

在這種情況下,您無需對每個字符輸入進行計數,您可以指定最大大小並完成操作。 就像是

 fgets(password, MAXCHAR, stdin);

可以為您完成工作,而無需為每個元素分配循環和分配。

但是要記住一件事,對於比給定長度短的輸入, fgets()也會讀取並存儲尾隨的換行符,您可能需要手動刪除它。 閱讀鏈接的手冊頁以獲取更多想法。

也就是說,對於托管環境, main()非常糟糕幾乎是非標准的 您應該至少使用int main(void)來符合標准。

所有C風格的字符串都有一個結尾\\0字符(值0)。 這對於任何其他字符值都是唯一的,因此可以用來表示字符串的結尾。 您觀察到的笑臉只是某些相鄰存儲塊的一部分,該存儲塊恰好在第一個字節后具有空字符(因此,只有一個額外的字符)。 printf函數從給定的字符串中讀取字節,直到看到\\0為止。 要解決您的問題,您可以寫

password[MAXCHAR] = '\0';

(您需要在數組中為\\0保留一個額外的字節)。

或者,您可以從一開始就將陣列歸零:

char password[MAXCHAR + 1] = { };

或使用memset

memset(password, '\0', sizeof password);

暫無
暫無

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

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