D
der
Hello all,
I want to use fgets() to read lines.
Now, if the user has entered more characters than it was supposed to,
the next call to fgets() would read
these characters, which I don't want to be read, but rather
reading fresh new line instead.
How should I deal with such scenario?
Here is my way of solving this problem.
I would like to know what you think about it.
void
getline(char *s, int size)
{
int len;
int correct_input;
do {
correct_input = 1;
fgets(s, size, stdin);
len = strlen(s);
if (len == size-1 && s[len-1] != '\n') {
/* if we have read size-1 characters, and the next
* one was '\n', delete it from stdin's buffer, and
* exit the loop.
*/
if (getchar() == '\n')
break;
/* If we are here, we have read too many characters.*/
correct_input = 0;
while (getchar() != '\n')
;
}
if (!correct_input)
printf("line is too big, please enter shorter"
" line.\n");
} while (!correct_input);
}
Thanks in advance,
der
I want to use fgets() to read lines.
Now, if the user has entered more characters than it was supposed to,
the next call to fgets() would read
these characters, which I don't want to be read, but rather
reading fresh new line instead.
How should I deal with such scenario?
Here is my way of solving this problem.
I would like to know what you think about it.
void
getline(char *s, int size)
{
int len;
int correct_input;
do {
correct_input = 1;
fgets(s, size, stdin);
len = strlen(s);
if (len == size-1 && s[len-1] != '\n') {
/* if we have read size-1 characters, and the next
* one was '\n', delete it from stdin's buffer, and
* exit the loop.
*/
if (getchar() == '\n')
break;
/* If we are here, we have read too many characters.*/
correct_input = 0;
while (getchar() != '\n')
;
}
if (!correct_input)
printf("line is too big, please enter shorter"
" line.\n");
} while (!correct_input);
}
Thanks in advance,
der