Not a stupid question at all. There's a few solutions.
You could make your input buffer reasonably large so it is unlikely to be too small. If you need to store many strings you can dynamically allocate space and copy the string from the large input buffer to the allocated space.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 500
int main() {
char line[1024];
char *lines[MAX_LINES];
size_t nlines = 0;
while (fgets(line, sizeof line, stdin)) {
if (nlines >= MAX_LINES) {
printf("lines overflow\n");
break;
}
lines[nlines] = malloc(strlen(line) + 1);
if (!lines[nlines]) {
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(lines[nlines], line);
++nlines;
}
for (size_t i = 0; i < nlines; ++i)
printf("%s", lines[i]);
for (size_t i = 0; i < nlines; ++i)
free(lines[i]);
return 0;
}
You can use a POSIX function (not in the standard library) that dynamically allocates the buffer for you.
Code:
// https://man7.org/linux/man-pages/man3/getline.3.html
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
int main() {
char *line = NULL;
size_t n = 0;
if (getline(&line, &n, stdin) == -1)
perror("getline");
else {
printf("%zu: %s", n, line);
free(line):
}
return 0;
}
Or you could write your own based on fgets, recalling that if the line that you've read doesn't have a newline (and eof hasn't been reached) then there's more to go. I just whipped this up so it may have a bug or two.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *readline(FILE *in) {
char buff[100], *line = NULL;
size_t size = 0;
while (fgets(buff, sizeof buff, in)) {
size_t len = strlen(buff);
char *tmp = realloc(line, size + len + 1);
if (!tmp) {
free(line);
return NULL;
}
line = tmp;
strcpy(line + size, buff);
size += len;
if (line[size - 1] == '\n') {
line[size - 1] = '\0'; // remove '\n' if desired
break;
}
}
return line;
}
int main() {
char *line = readline(stdin);
if (!line) {
printf("readline allocation error\n");
exit(EXIT_FAILURE);
}
printf("%zu: %s\n", strlen(line), line);
free(line);
return 0;
}