I have been trying to learn C, and was wondering: how would one get a string with an unknown length in C? I have found some results, but am not sure how to apply them.
Asked
Active
Viewed 363 times
0
-
2Get from where? – Eugene Sh. Apr 11 '19 at 21:05
-
C has char arrays, you should declare char array based on length of the string. – Marios Nikolaou Apr 11 '19 at 21:05
-
Assuming you are asking about user input - you can read char by char (or by length limited chunks) in a loop and dynamically allocate/reallocate space to store it. – Eugene Sh. Apr 11 '19 at 21:09
-
1Which results have you found? How did you try to apply them? What was the problem with applying them? Where's the code — an MCVE ([MCVE]) — that shows the problem you're having applying what you think is the best solution? – Jonathan Leffler Apr 11 '19 at 21:14
-
Not sure why anyone voted this as "unclear what you're asking", it seems very clear to me – M.M Apr 12 '19 at 02:33
-
That's the one I saw. I didn't know how to apply it – nerdguy Apr 12 '19 at 11:10
1 Answers
0
If you're ok with extensions to the Standard, try POSIX getline()
.
Example from documentation:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(1);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
if (ferror(fp)) {
/* handle error */
}
free(line);
fclose(fp);
return 0;
}

pmg
- 106,608
- 13
- 126
- 198