Sujet : Re: Whaddaya think?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 16. Jun 2024, 05:17:57
Autres entêtes
Organisation : None to speak of
Message-ID : <877cep4j2i.fsf@nosuchdomain.example.com>
References : 1 2 3 4
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Janis Papanagnou <janis_papanagnou+
ng@hotmail.com> writes:
On 16.06.2024 05:26, Lawrence D'Oliveiro wrote:
On Sun, 16 Jun 2024 01:56:49 +0300, Michael S wrote:
If you want to preserve you sanity, never use fscanf().
Quoth the man page <https://manpages.debian.org/3/scanf.3.en.html>:
It is very difficult to use these functions correctly, and it is
preferable to read entire lines with fgets(3) or getline(3) and
parse them later with sscanf(3) or more specialized functions such
as strtol(3).
>
This would be also my first impulse, but you'd have to know
_in advance_ how long the data stream would be; the function
requires an existing buffer. So you'd anyway need a stepwise
input. On the plus side there's maybe a better performance
to read large buffer junks and compose them on demand? But
a problem is the potential cut of the string of a number; it
requires additional clumsy handling. So it might anyway be
better (i.e. much more convenient) to use fscanf() ?
I advise never using any of the *scanf() functions for numeric input
unless you have control over what appears on the input stream.
They have undefined behavior if the input value is out of range.
(I consider this a bug in the language.) Typical behavior is to
store some arbitrary integer value with no error indication.
As for reading lines, getline() can allocate a buffer long enough
to hold the line, but it's defined by POSIX, not by ISO C.
For the original problem, where the input consists of digits and
whitespace, you could read a character at a time and accumulate the
value of each number. (You probably want to handle leading signs as
well, which isn't difficult.) That is admittedly reinventing the
wheel, but the existing wheels aren't entirely round. You still
have to dynamically allocate the array of ints, assuming you need
to store all of them rather than processing each value as it's read.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */