473,700 Members | 2,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 7255

"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********@yah oo.com) (cb********@wor ldnet.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********@yah oo.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********@yah oo.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
1918
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 following code (example from the php Manual.) The Problem is: I read from the standard output with echo stream_get_contents($pipes); this function is available only from PHP version 5, but I must write for version 4.3.0. Which way could it be solved?...
19
10618
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 do readline(). Is there a way to do this? for example: while 1: line=stdin.peek_nextline()
15
7971
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 <stdio.h> #include <ctype.h> #include <stdlib.h> int main(){
7
13261
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
6855
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: 1) get whole string of input line 2) preset table of strings matching <command> 3) preset table of function calls
9
5209
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 facing problems: Assume that FILE* filePointer; unsigned char lineBuffer;
11
2454
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 number of effective cars, ask the user to input each car data (i.e. make, model, year and price). You can assume that all input data is correct and no data validation is necessary. As soon as all input data for a car is entered, build a Car object by...
6
2522
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 a car and put them into an array called carShop. This part of the program is running fine. Every thing in the CarDealerApp.java file runs correctly except for the last loop. I need to read in through user input the make of a car and then search the...
0
1357
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 server-side component (written in C) that 'listens' for PHP requests (via its stdin) and spits out the appropriate response (via its stdout). Conversely, the PHP side uses fwrite() to send to the component's stdin and fread() to read from the component's...
0
8712
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8639
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9203
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8952
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8911
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6555
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5895
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3082
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2375
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.