Is it possible to read lines of text with scanf() - excluding \n and break on special(chosen) character, but include that character(?)
Yes. But scanf()
is notorious for being used wrong and difficult to use right. Certainly the scanf()
approach will work for most user input. Only a rare implementation will completely meet OP's goal without missing corner cases. IMO, it is not worth it.
Alternatively, let us try the direct approach, repeatedly use fgetc()
. Some untested code:
char *luvatar_readline(char *destination, size_t size, char special) {
assert(size > 0);
char *p = destitution;
int ch;
while (((ch = fgetc(stdin)) != EOF) && (ch != '\n')) {
if (size > 1) {
size--;
*p++ = ch;
} else {
// Ignore extra input or
// TBD what should be done if no room left
}
if (ch == (unsigned char) special) {
break;
}
}
*p = '\0';
if (ch == EOF) {
// If rare input error
if (ferror(stdin)) {
return NULL;
}
// If nothing read and end-of-file
if ((p == destination) && feof(stdin)) {
return NULL;
}
}
return destination;
}
Sample usage
char buffer[50];
while (luvatar_readline(buffer, sizeof buffer_t, ':')) {
puts(buffer);
}
Corner cases TBD: Unclear what OP wants if special
is '\n'
or '\0'
.
OP's while(scanf("%49[^:\n]%*c", x)==1)
has many problems.
Does not cope with input the begins with :
or '\n'
, leaving x
unset.
Does not know if the character after the non-:
, non-'\n'
input was a :
, '\n'
, EOF.
Does not consume extra input past 49.
Uses a fixed spacial character ':'
, rather than a general one.