简体   繁体   中英

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:

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.

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; } part doesn't look good, so here is another code example:

#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.

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. Read the linked man page for more ideas.

That said, main() is a very bad and almost non-standard for hosted environments. You should use int main(void) , at least to conform to the standards.

All C-style strings have a terminal \\0 character (value 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 . 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 ).

Or you can zero-out your array from the get-go:

char password[MAXCHAR + 1] = { };

Or using memset :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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