I want to read in a variable number of strings in C using the
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
function. So I came up with the following code:
int main() {
int number;
char *line;
size_t len;
scanf("%d", &number);
for (int i = 0; i < number; ++i) {
line = NULL;
getline(&line, &len, stdin);
printf("%s", line);
}
}
The problem, with above code is, that the first call of getline reads in the newline character ('\n'
) which follows the entered number instead of the first string. Adding one of the following lines of code (denoted by OPTION 1 resp. OPTION 2
) fixes the problem:
int main() {
int number;
char *line;
size_t len;
scanf("%d", &number);
// fflush(stdin); /* OPTION 1 */
for (int i = 0; i < number; ++i) {
line = NULL;
getline(&line, &len, stdin);
// while (*line == '\n') getline(&line, &len, stdin); /* OPTION 2 */
printf("%s", line);
}
}
My Questions:
Is adding one of these lines (
OPTION 1, OPTION 2
) the correct way of doing this?If so which one is to favor over the other?
If not what would be the correct way?