Name: Anonymous 2013-03-14 2:49
As we know, gets() is unsafe, fgets() annoyingly retains the '\n', getline() is non-standard, and scanf() always stops at spaces. Many of us wind up rolling our own.
This one
1. always NUL-terminates
2. is efficient since there are only two tests in the main loop
3. discards everything until the end of the line if truncation occurs.
void
getstr(char *s, size_t siz)
{
int c;
char *max = s + siz - 1;
while ((c = getchar()) != '\n' && s < max)
*s++ = c;
*s = '\0';
while (c != '\n')
c = getchar();
}
This one
1. always NUL-terminates
2. is efficient since there are only two tests in the main loop
3. discards everything until the end of the line if truncation occurs.
void
getstr(char *s, size_t siz)
{
int c;
char *max = s + siz - 1;
while ((c = getchar()) != '\n' && s < max)
*s++ = c;
*s = '\0';
while (c != '\n')
c = getchar();
}