简体   繁体   English

C-限制字符串长度

[英]C - Limit the string length

(Sorry for my bad english !) (对不起,我的英语不好 !)

I wrote a program that asks you to type a password no longer than a certain number, eight characters in this case. 我写了一个程序,要求您输入密码,密码不能超过一个特定的数字,在这种情况下为八个字符。 The characters that pass the limit will be cut out from the array: 超过限制的字符将从数组中切出:

#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);
}

So the program works BUT there is a "strange" problem. 因此该程序可以运行,但是存在“奇怪”问题。 If the limit IS EIGHT and I type a password longer than eight characters (Example: P455w0rds98) the output will be like this: 如果限制为EIGHT,并且我输入的密码长于八个字符(例如:P455w0rds98),则输出将如下所示:

P455w0rd☺

So it puts a smiley at the end and I don't know why. 所以结尾处带有笑脸,我不知道为什么。 It happens only if a the limit is established at eight. 仅当将限制设置为8时才会发生。

You must specify the length to print or terminate the string. 您必须指定打印或终止字符串的长度。 Otherwise, you will invoke undefined behavior . 否则,您将调用未定义的行为 Try this, in which the latter method is implemented. 尝试执行后一种方法。

#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);
}

Some people say that the if(i == MAXCHAR){ break; } 有人说if(i == MAXCHAR){ break; } if(i == MAXCHAR){ break; } part doesn't look good, so here is another code example: 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);
}

Apart from the answer you already received from MikeCAT , an alternate approach would be to make use of fgets() to read the user input. 除了您已经从MikeCAT收到的答案之外 ,另一种方法是利用fgets()读取用户输入。

In that case , you don't need to keep a count on each character input, you can specify the max size and get done with it. 在这种情况下,您无需对每个字符输入进行计数,您可以指定最大大小并完成操作。 Something like 就像是

 fgets(password, MAXCHAR, stdin);

can get the job done for you, minus the looping and assignment for each element. 可以为您完成工作,而无需为每个元素分配循环和分配。

One thing to remember, however, for shorter inputs than the given length, fgets() reads and stores the trailing newline also, you may need to get rid of that manually. 但是要记住一件事,对于比给定长度短的输入, fgets()也会读取并存储尾随的换行符,您可能需要手动删除它。 Read the linked man page for more ideas. 阅读链接的手册页以获取更多想法。

That said, main() is a very bad and almost non-standard for hosted environments. 也就是说,对于托管环境, main()非常糟糕几乎是非标准的 You should use int main(void) , at least to conform to the standards. 您应该至少使用int main(void)来符合标准。

All C-style strings have a terminal \\0 character (value 0). 所有C风格的字符串都有一个结尾\\0字符(值0)。 This is unique from any other character value, so it can be used to signal the end of the string. 这对于任何其他字符值都是唯一的,因此可以用来表示字符串的结尾。 The smiley face you observe is just a part of some neighboring memory block that happens to have a null character after the first byte (hence there being only one extra character). 您观察到的笑脸只是某些相邻存储块的一部分,该存储块恰好在第一个字节后具有空字符(因此,只有一个额外的字符)。 The printf function reads bytes from the string given to it, until it sees the \\0 . printf函数从给定的字符串中读取字节,直到看到\\0为止。 To solve your problem, you can either write 要解决您的问题,您可以写

password[MAXCHAR] = '\0';

(You will need to reserve one additional byte in your array, for the \\0 ). (您需要在数组中为\\0保留一个额外的字节)。

Or you can zero-out your array from the get-go: 或者,您可以从一开始就将阵列归零:

char password[MAXCHAR + 1] = { };

Or using memset : 或使用memset

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM