using strlen to find length of user input c [closed]

╄→尐↘猪︶ㄣ 提交于 2019-12-13 23:30:41

问题


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?


回答1:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/36652985/using-strlen-to-find-length-of-user-input-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!