using strlen to find length of user input c [close

2019-09-20 11:19发布

I am trying to create an array that to store a user's input, and I need the array to be the exact length of the user's input. I would like to take the length of the user's input, and use this as the length of the array. How can I do this with strlen? Is there any better way?

2条回答
趁早两清
2楼-- · 2019-09-20 11:59

This is one way to acquire memory as you need it. I would use CHUNKSIZE more than 4 but I restricted it for easy testing.

#include <stdio.h>
#include <stdlib.h>

#define CHUNKSIZE   4

int main(void){
    char *text;
    int maxlen = CHUNKSIZE;
    int index = 0;
    int ch;

    text = malloc(CHUNKSIZE);
    if(text == NULL)
        exit(1);
    printf("Enter your text:\n");

    while((ch = getchar()) != EOF && ch != '\n') {
        text[index++] = ch;
        if (index >= maxlen) {
            maxlen += CHUNKSIZE;
            text = realloc(text, maxlen);   
            if(text == NULL)
                exit(1);
        }
    }
    text[index] = 0;                // terminate

    printf("%d You entered: %s\n", maxlen, text);
    free(text);    
    return 0;
}

Program session:

Enter your text:
A quick brown fox jumps over the lazy dog.
You entered: A quick brown fox jumps over the lazy dog.
查看更多
一夜七次
3楼-- · 2019-09-20 12:01

Before writing your own function, you can try the following code:

char *str;
scanf("%ms", &str); // <--- Note the & before str

// Do something with str...

free(str);

This is an extension to ISO C standard supported on all POSIX.1-2008-conforming systems.

查看更多
登录 后发表回答