[easy] reading into an array

S

Susan Sherpi

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.

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

Thanks -Susan
 
E

Eric Sosman

Susan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top