C - 限制字符串长度

Cla*_*isa 3 c arrays loops

(对不起,我的英语不好 !)

\n\n

我编写了一个程序,要求您输入不超过特定数字的密码,在本例中为八个字符。超过限制的字符将从数组中删除:

\n\n
#include <stdio.h>\n#define MAXCHAR 8\n\nmain()\n{\n    char password[MAXCHAR];\n    int i;\n    char c;\n\n    printf("Insert password: MAX 8 CHARS!\\n\\n");\n    for(i = 0; i <= MAXCHAR; i++){\n        c = getchar();\n\n        if(i == MAXCHAR){\n            break;\n        }\n        else{\n            password[i] = c;\n        }\n    }\n\n    printf("%s\\n", password);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以该程序可以运行,但存在一个“奇怪”的问题。如果限制是八个并且我输入的密码超过八个字符\n(示例:P455w0rds98)\n输出将如下所示:

\n\n
P455w0rd\xe2\x98\xba\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以它在最后放了一个笑脸,我不知道为什么。仅当限制设置为八时才会发生这种情况。

\n

Mik*_*CAT 5

您必须指定打印或终止字符串的长度。否则,您将调用未定义的行为。试试这个,其中实现了后一种方法。

#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);
}
Run Code Online (Sandbox Code Playgroud)

有人说这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);
}
Run Code Online (Sandbox Code Playgroud)