Velocity Reviews > [easy] reading into an array

# [easy] reading into an array

Susan Sherpi
Guest
Posts: n/a

 10-17-2003
Hello,

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.

Can someone tell me what's wrong with this function:

----------------------------
{
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.

I bet there's a standard library function for this, too - is there?

Thanks -Susan

Eric Sosman
Guest
Posts: n/a

 10-17-2003
Susan Sherpi wrote:
>
> Hello,
>
> 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.
>
> Can someone tell me what's wrong with this function:
>
> ----------------------------
> 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. So if the first input line has
five numbers, the first five calls to scanf() will consume
and convert them. The sixth call will see the newline, skip
over it, and start trying to read from the second input line.
This use of scanf() will keep on returning 1 until it finds
a non-white character that cannot be part of an integer,
something like an 'x' or a '?' (or end-of-file). As long as
you keep feeding it numbers and white space, it will keep on
consuming them and keep on asking for more.

> I bet there's a standard library function for this, too - is there?

There's probably some way to use scanf() with the "%["
specifier to do what you want, but if so it'll be ugly. 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). You could use sscanf() instead of
strtol(), but it'd be marginally more complicated.

--
http://www.velocityreviews.com/forums/(E-Mail Removed)