S
Susan Sherpi
Hi. Thanks to Eric Sosman for showing me what was wrong with my code in an
earlier posting. He wrote, quoting me:
Ah yes that seems obvious now. I suppose I could just have the user end a
line of input with a random non-whitespace non-numeric character - would
make my life easier, but seems like a dumb solution.
Thanks. First I tried using sscanf on the output of fgets, but it just
kept reading the first number in the string, of course... I see strtol is
designed for this, great, but the documentation I have on strtol is so
terse, I'm afraid I can't figure out how to call it repeatedly. I
understand it reads as much of the string as it can convert into a number,
then returns a pointer to the beginning of the unused portion of the
string so the next call can start where the last one left off. Could some
kind soul show me an example of repeated calls to strtol? And can I have
strtol use both whitespace and commas as alternative field delimiters?
Susan
earlier posting. He wrote, quoting me:
I want to read a line of decimal integers from standard input into an
array, stopping when a newline is encountered, and I'd like the
function to return the number of values read in.
----------------------------
int read_array(int p[])
{
j=0;
while(scanf("%d",&p[j])==1)
j++;
return j;
}
----------------------------
I thought that as soon as scanf found a character that wasn't a decimal
number, it wouldn't be able to put it in the array and would return 0,
and I'd bust out of the while loop - but that doesn't happen.
As used here, scanf() skips white space -- and newlines
are considered white space.
Ah yes that seems obvious now. I suppose I could just have the user end a
line of input with a random non-whitespace non-numeric character - would
make my life easier, but seems like a dumb solution.
I'd suggest using two functions: read an entire single line with
fgets(), and then use strtol() repeatedly to convert the numbers
(and check for garbage).
Thanks. First I tried using sscanf on the output of fgets, but it just
kept reading the first number in the string, of course... I see strtol is
designed for this, great, but the documentation I have on strtol is so
terse, I'm afraid I can't figure out how to call it repeatedly. I
understand it reads as much of the string as it can convert into a number,
then returns a pointer to the beginning of the unused portion of the
string so the next call can start where the last one left off. Could some
kind soul show me an example of repeated calls to strtol? And can I have
strtol use both whitespace and commas as alternative field delimiters?
Susan