Is it possible to read lines of text using scanf () - excluding \ n and splitting it into a special (selected) character, but including this character (?)
Yes. But scanf()
is known for being used incorrectly and is difficult to use correctly. Of course, the scanf()
approach will work for most users. Only a rare implementation is fully consistent with the OP goal without missing corner cases. IMO, this is not worth it.
As an alternative, we will try a direct approach, we will repeatedly use fgetc()
. Invalid 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; }
Using example
char buffer[50]; while (luvatar_readline(buffer, sizeof buffer_t, ':')) { puts(buffer); }
Corner cases of TBD: It is not clear what the OP wants if special
is '\n'
or '\0'
.
OP while(scanf("%49[^:\n]%*c", x)==1)
has many problems.
Cannot cope with input, starts with :
or '\n'
, leaving x
unset.
Doesn't know if the character after the input :
non '\n'
equal to :
'\n'
, EOF.
Does not consume additional input for 49.
Uses a fixed spatial character ':'
, not a common one.
source share