Input unknown number of integers in a line...

N

none

If I need to add up all integers in a line (they're separated by space)
How can I do that??

e.g.
input : 1 4 5 2 3
sum : 15
input : 2 3
sum: 5
 
N

none

I searched for functions..
but still can't find any clues..

My first thought is scanf the whole line,
and use itoa function to add the integers one by one,
but how can I isolate the substring and use itoa function to turn it
into integer??

just like,
10 23 234
I can detect the 2 spaces,
so I need to cut the 2 characters and place it to another character array??





Ben Pfaff mentioned:
 
N

none

Thx~



Ben Pfaff mentioned:
I think you are trying to work too hard. There is no reason to
read the entire line all at once. Read and accumulate one number
at a time.
 
B

Ben Pfaff

none said:
If I need to add up all integers in a line (they're separated by space)
How can I do that??

You could write a C program to do it. Have you tried?
 
B

Ben Pfaff

none said:
My first thought is scanf the whole line,
and use itoa function to add the integers one by one,
but how can I isolate the substring and use itoa function to turn it
into integer??

I think you are trying to work too hard. There is no reason to
read the entire line all at once. Read and accumulate one number
at a time.
 
L

Lawrence Kirby

I assume you mean atoi(), C has no itoa() function.
I think you are trying to work too hard. There is no reason to
read the entire line all at once. Read and accumulate one number
at a time.

Reading in the whole line using fgets() is a good approach. You could read
in a number at a time using scanf() but then it is more difficult to work
out when you have reached the end of the line, and make sure you haven't
left any training characters in the stream. After reading with fgets() you
could use strtok() to get the test for each number and convert using
atoi() or strtol().

Lawrence
 
C

CBFalconer

Lawrence said:
I assume you mean atoi(), C has no itoa() function.


Reading in the whole line using fgets() is a good approach. You could read
in a number at a time using scanf() but then it is more difficult to work
out when you have reached the end of the line, and make sure you haven't
left any training characters in the stream. After reading with fgets() you
could use strtok() to get the test for each number and convert using
atoi() or strtol().

Better yet use ggets() and forget about buffer sizes etc. The
result is always a writable string. See:

<http://cbfalconer.home.att.net/download/ggets.zip>
 
B

Ben Pfaff

Ben Pfaff said:
I think you are trying to work too hard. There is no reason to
read the entire line all at once. Read and accumulate one number
at a time.

In fact, it's easy enough with only one *digit* at a time:

#include <stdio.h>
#include <ctype.h>

/* Read integers from stdin, print their sum to stdout. */
int
main (void)
{
unsigned total = 0, current = 0;

for (;;) {
int c = getchar ();
if (c == EOF)
break;
else if (isdigit (c))
current = current * 10 + (c - '0');
else {
total += current;
current = 0;
}
}
printf ("%u\n", total + current);
return 0;
}
 
C

CBFalconer

Ben said:
In fact, it's easy enough with only one *digit* at a time:

#include <stdio.h>
#include <ctype.h>

/* Read integers from stdin, print their sum to stdout. */
int
main (void)
{
unsigned total = 0, current = 0;

for (;;) {
int c = getchar ();
if (c == EOF)
break;
else if (isdigit (c))
current = current * 10 + (c - '0');
else {
total += current;
current = 0;
}
}
printf ("%u\n", total + current);
return 0;
}

This brings up a point to me. Obviously the first control
structure that came to your mind was a for loop. To me, I would
start with a while loop, as below.

while (EOF != (c = getchar())) {
}

and only then would I expand the loop, and your code looks just
fine for the purpose, into:

while (EOF != (c = getchar())) {
if (isdigit (c)) current = current * 10 + (c - '0');
else {
total += current;
current = 0;
}
}
printf ("%u\n", total + current);
return 0;

Obviously neither is wrong, but why is there such a basic
difference in the selection of code structure?
 
B

Ben Pfaff

CBFalconer said:
Obviously the first control structure that came to your mind
was a for loop. To me, I would start with a while loop, as
below.

while (EOF != (c = getchar())) {
}

and only then would I expand the loop...

As a stylistic issue, I just don't like to combine assignments
and tests. I can understand it just fine, of course, but I
usually avoid doing it in my own code. That's the only reason I
use `for' instead of `while' in that code.
 
C

CBFalconer

Ben said:
As a stylistic issue, I just don't like to combine assignments
and tests. I can understand it just fine, of course, but I
usually avoid doing it in my own code. That's the only reason I
use `for' instead of `while' in that code.

You chose an infinite loop, with a test to break out of it. This
doesn't emphasize the exit condition, as opposed to a loop which
describes the exit point. It doesn't have to have an embedded
assignment. Remember, I am not criticizing, I am just
investigating the thought processes involved.

c = getchar();
while (EOF != c) {
....
c = getchar();
}
 
B

Ben Pfaff

CBFalconer said:
You chose an infinite loop, with a test to break out of it. This
doesn't emphasize the exit condition, as opposed to a loop which
describes the exit point. It doesn't have to have an embedded
assignment. Remember, I am not criticizing, I am just
investigating the thought processes involved.

There are pros and cons to each approach. I can read and write
code in either style. I try to conform to the existing style
when I contribute to projects.

I tend to write most of my code for GNU projects; the GNU coding
standards discourage assignments in `if' conditions, and I've
always mentally extended that to looping constructs. Over the
last few years I've begun to realize why it's not really the same
situation, but the habit is ingrained.

On the other hand, when I write code at a particular company
founded by my PhD advisor, I would use a `while' loop with an
assignment, because that coding style is common there. There, I
would write the program something like this:

/*
* sumStdin.c
*
* Brief description:
* Sums integers from stdin and prints the sum to stdout.
*
* Copyright (C) 2005 BigCorp Subsidiary, Inc.
*/
#include <stdio.h>
#include <ctype.h>

/*
* main()
*
* Description:
* Reads integers from stdin and prints their sum on stdout.
*
* Return value:
* Always returns 0.
*
* Side effects:
* I/O.
*/
int
main(void)
{
unsigned total = 0, current = 0;
int c;

while ((c = getchar()) != EOF) {
if (isdigit(c)) {
current = current * 10 + (c - '0');
} else {
total += current;
current = 0;
}
}
printf("%u\n", total + current);
return 0;
}
 
C

Chris Croughton

Obviously neither is wrong, but why is there such a basic
difference in the selection of code structure?

"There are nine and ninety ways / to sing the tribal ways / and every
single one of them is right!" [Kipling, from memory]

Some might use a do...while loop, or use a goto, or many other things.
In engineering there is seldom /a/ right way, there are definitely
wrong ways (anything which doesn't work is wrong, no matter how elegant)
but otherwise it is largely an aesthetic choice or a matter of taste.
De gustibus nil disputandem est...

Chris C
 
R

Randy Howard

This brings up a point to me. Obviously the first control
structure that came to your mind was a for loop. To me, I would
start with a while loop, as below.

while (EOF != (c = getchar())) {
}

and only then would I expand the loop, and your code looks just
fine for the purpose, into:

while (EOF != (c = getchar())) {
if (isdigit (c)) current = current * 10 + (c - '0');
else {
total += current;
current = 0;
}
}
printf ("%u\n", total + current);
return 0;

Obviously neither is wrong, but why is there such a basic
difference in the selection of code structure?

Because you are a pascal programmer at heart?
 
K

Kenny McCormack

Chris Croughton said:
Some might use a do...while loop, or use a goto, or many other things.
In engineering there is seldom /a/ right way, there are definitely
wrong ways (anything which doesn't work is wrong, no matter how elegant)
but otherwise it is largely an aesthetic choice or a matter of taste.
De gustibus nil disputandem est...

In the real world (outside of academia and/or newsgroups), anything that
works is "right" (this is a logical extension of "anything that doesn't
work is wrong"). Trust me. I know of what I speak.

So, I would edit what you said above to:

..., there is seldom a right way, there is usually a *best* way
 
R

Richard Bos

In the real world (outside of academia and/or newsgroups), anything that
works is "right" (this is a logical extension of "anything that doesn't
work is wrong"). Trust me. I know of what I speak.

No, you don't. Anything that _seems_ to work may be "right" by
management standards, but from a sysadmin's POV, it's only right if it
continues to work even if you a. change the hardware, b. change the OS
version (e.g., from Win98 to WinXP), and c. stop manually fiddling
around the effects of blatant bugs.

Richard
 
C

Chris Croughton

In the real world (outside of academia and/or newsgroups), anything that
works is "right" (this is a logical extension of "anything that doesn't
work is wrong"). Trust me. I know of what I speak.

Not as an absolute, no, there are many places where things not adhering
to things like coding styles are 'wrong' no matter how well they work.
Including trivia like whether you use x * 2 or x >> 1 (where I work now
I've been not allowed to check in a source file because the person
inspecting it saw that I'd used the x*2 form!).
So, I would edit what you said above to:

..., there is seldom a right way, there is usually a *best* way

Not even that. Which is 'best' out of "x * 2" and "x << 1"? There may
be occasions when one is marginally more efficient or more maintainable
than the other, but very often "more maintainable" is in the eye of the
beholder and efficiency depends on the details of the environment.

There is seldom a 'right' way, there is usually some way which someone
(if you're unlucky, your boss) feels is the 'best' way with no reason
other than "I prefer it"...

Chris C
 
E

Eric Sosman

Chris said:
Not as an absolute, no, there are many places where things not adhering
to things like coding styles are 'wrong' no matter how well they work.
Including trivia like whether you use x * 2 or x >> 1 (where I work now
I've been not allowed to check in a source file because the person
inspecting it saw that I'd used the x*2 form!).

Had I been the inspector, I would also have forbidden
the use of `x * 2' as a substitute for `x >> 1' -- assuming
I was alert that day, of course.
 
C

Christopher Benson-Manica

Eric Sosman said:
Had I been the inspector, I would also have forbidden
the use of `x * 2' as a substitute for `x >> 1' -- assuming
I was alert that day, of course.

You certainly seem to be alert today :)
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top