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.