473,322 Members | 1,409 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

line of array from stdin

Hi. Thanks to Eric Sosman for showing me what was wrong with my code in an
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

Nov 13 '05 #1
5 7233

"Susan Sherpi" <ss@example.com> wrote in message
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.

/*
read a line of integers from stdin.
Inputs ret - return pointer for integers read.
len - size of the buffer (for safety)
Returns: No integer read if successful, -1 on error
*/
int readint(int *ret, int len)
{
char buff[1024];
char *ptr;
char *tmp;
int answer = 0;

/* read a line, return -1 if error */
if( fgets(buff, 1024, stdin) == NULL)
return -1;

/* return -1 if fgets() didn't read the whole line */
if(!strchr(buff, '\n'))
return -1;

ptr = buff;
/* skip leading whitespace */
while(isspace(*ptr))
ptr++;

/* do out loop until ptr points to the terminating NUL */
while(*ptr)
{
/* read an integer */
/* the pointer tmp holds the first non-digit strtol encountered */
ret[answer] = (int) strtol(ptr, &tmp, 10);
/* if tmp equals ptr we have garbage and not a number */
if(tmp == ptr)
return -1;
ptr = tmp;
answer++;
/* here's a bit for you to do. You need to check for whitespace and
commas, and skip ptr so it jumps over them */
/* you also want to check that answer isn't greater or equal to len */
}
/* return the number of integers we read */
return answer;
}
Nov 13 '05 #2
Susan Sherpi wrote:

Hi. Thanks to Eric Sosman for showing me what was wrong with my
code in an 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.
.... snip ...
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


To make sscanf advance, try the following. You can get the source
of ggets at:

<http://cbfalconer.home.att.net/download/>

#include <stdio.h>
#include <stdlib.h>
#include "ggets.h"

int countints(void)
{
char *ln;
int num;
int count;
int ix, delta;

count = 0; ix = 0;
if (0 == ggets(&ln)) {
while (1 == sscanf(&ln[ix], "%d%n", &num, &delta)) {
printf("[%d]%d ", ix, num);
ix += delta;
count++;
}
printf(": %d\n", count);
free(ln);
}
return count;
} /* countints */

/* ------------------ */

int main(void)
{
while (countints()) continue;
return 0;
} /* main */

You can easily gussy things up to store the values in an array.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 13 '05 #3
Malcolm wrote:

"Susan Sherpi" <ss@example.com> wrote in message
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.

/*
read a line of integers from stdin.
Inputs ret - return pointer for integers read.
len - size of the buffer (for safety)
Returns: No integer read if successful, -1 on error
*/
int readint(int *ret, int len)
{
char buff[1024];
char *ptr;
[...]
ptr = buff;
/* skip leading whitespace */
while(isspace(*ptr))
ptr++;
[... and then apply strtol(ptr,...) ...]


There are two problems here: One outright error and one
inefficiency.

The error is that isspace() and friends take an `int'
argument whose value is either EOF (not an issue here) or
the value of an `unsigned char'. On a system where plain
`char' is signed, the conversion of `*ptr' to an `int'
can produce negative values, which are clearly not within
the range of an `unsigned char', and demons will fly out
of your nose. Write instead

while (isspace( (unsigned char)*ptr ))

The inefficiency is that strtol() skips leading white
space all by itself without external help; the loop is
altogether unnecessary! (I imagine it was inserted in
the sample code to satisfy a requirement laid down by
the Department of Redundancy Dept.)

--
Er*********@sun.com
Nov 13 '05 #4
CBFalconer <cb********@yahoo.com> wrote:
Susan Sherpi wrote:

Hi. Thanks to Eric Sosman for showing me what was wrong with my
code in an 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.
>>

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


To make sscanf advance, try the following. You can get the source
of ggets at:

<http://cbfalconer.home.att.net/download/>

#include <stdio.h>
#include <stdlib.h>
#include "ggets.h"

int countints(void)
{
char *ln;
int num;
int count;
int ix, delta;

count = 0; ix = 0;
if (0 == ggets(&ln)) {
while (1 == sscanf(&ln[ix], "%d%n", &num, &delta)) {

Thanks --what is the %n format specifier? it's not on my list

Susan
Nov 13 '05 #5


On 10/20/2003 11:18 AM, Susan Sherpi wrote:
CBFalconer <cb********@yahoo.com> wrote:
<snip>
while (1 == sscanf(&ln[ix], "%d%n", &num, &delta)) {


Thanks --what is the %n format specifier? it's not on my list


You can look it up on-line at:

http://www.acm.uiuc.edu/webmonkeys/b....12.html#scanf

Regards,

Ed.
Susan


Nov 13 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: kpohl | last post by:
Hi! It would be great if anyone could help me with this problem: I want to check the syntax of my php code. Therefore I use the command line function PHP -l, the structure is similar to the...
19
by: les_ander | last post by:
Hi, suppose I am reading lines from a file or stdin. I want to just "peek" in to the next line, and if it starts with a special character I want to break out of a for loop, other wise I want to...
15
by: Carramba | last post by:
hi! I am trying to confirm if input is digit, so I thought it would by easy to do it with with isdigit() funktion, but how do I pass arrays to it if the imput is more then 1 sign? #include...
7
by: gyan | last post by:
I want to read a line with white spaces though scanf. So i used: scanf("%",string); above is working in one program, but in other..what may be the reason?
34
by: Roman Mashak | last post by:
Hello, All! I'm implementing simple CLI (flat model, no tree-style menu etc.). Command line looks like this: <command> <param1> <param2> ... <paramN> (where N=1..4) And idea is pretty simple: ...
9
by: Adi | last post by:
Hello eveyone, I wanna ask a very simple question here (as it was quite disturbing me for a long time.) My problem is to read a file line by line. I've tried following implementations but still...
11
by: AZRebelCowgirl73 | last post by:
here is the instructiions I am to use Ask the user to input the number of effective cars in the shop (this number should be between 1 and 100, inclusively). In a loop, controlled by the inputted...
6
by: AZRebelCowgirl73 | last post by:
Here is my problem: I have two java files: One named Car.java and the other named CarDealerApp.java: In the CarDealerApp program, I read in through user input the make, model, year and price of...
0
by: Daniel Klein | last post by:
Without getting into a lot of unnecessary detail, I'm working on a project to allow PHP to communicate with a proprietary database. The IPC mechanism I'm using is 'proc_open'; there is a...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.