Input unknown number of integers in a line...

  • Follow


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
0
Reply none 1/27/2005 2:52:57 PM

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:
> none <""root\"@(none)"> writes:
> 
> 
>>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?
0
Reply none 1/27/2005 5:09:17 PM


Thx~



Ben Pfaff mentioned:
> none <""root\"@(none)"> writes:
> 
> 
>>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.
0
Reply none 1/27/2005 8:01:03 PM

none <""root\"@(none)"> writes:

> 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?
-- 
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa67f6aaa,0xaa9aa9f6,0x1f6},*p=
b,x,i=24;for(;p+=!*p;*p/=4)switch(x=*p&3)case 0:{return 0;for(p--;i--;i--)case
2:{i++;if(1)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
0
Reply blp (3953) 1/28/2005 3:35:45 AM

none <""root\"@(none)"> writes:

> 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.
-- 
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.\
 \n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
0
Reply blp (3953) 1/28/2005 5:30:44 AM

On Thu, 27 Jan 2005 21:30:44 -0800, Ben Pfaff wrote:

> none <""root\"@(none)"> writes:
> 
>> My first thought is scanf the whole line,
>> and use itoa function to add the integers one by one,

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

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

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

0
Reply lknews (877) 1/28/2005 12:13:50 PM

Lawrence Kirby wrote:
> On Thu, 27 Jan 2005 21:30:44 -0800, Ben Pfaff wrote:
> 
> > none <""root\"@(none)"> writes:
> >
> >> My first thought is scanf the whole line,
> >> and use itoa function to add the integers one by one,
> 
> I assume you mean atoi(), C has no itoa() function.
> 
> >> 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.
> 
> 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>

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


0
Reply cbfalconer (19183) 1/28/2005 3:46:20 PM

Ben Pfaff <blp@cs.stanford.edu> writes:

> 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;
}
-- 
"Welcome to the wonderful world of undefined behavior, where the demons
 are nasal and the DeathStation users are nervous." --Daniel Fox
0
Reply blp (3953) 1/28/2005 7:35:42 PM

Ben Pfaff wrote:
> Ben Pfaff <blp@cs.stanford.edu> writes:
> 
>> 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;
> }

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?

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


0
Reply cbfalconer (19183) 1/28/2005 11:25:34 PM

CBFalconer <cbfalconer@yahoo.com> writes:

> 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.
-- 
"If I've told you once, I've told you LLONG_MAX times not to
 exaggerate."
--Jack Klein
0
Reply blp (3953) 1/28/2005 11:52:53 PM

Ben Pfaff wrote:
> CBFalconer <cbfalconer@yahoo.com> writes:
> 
>> 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.

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();
    }

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


0
Reply cbfalconer (19183) 1/29/2005 4:08:40 AM

CBFalconer <cbfalconer@yahoo.com> writes:

> Ben Pfaff wrote:
>> CBFalconer <cbfalconer@yahoo.com> writes:
>> 
>>> 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.
>
> 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;
}
-- 
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.\
 \n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
0
Reply blp (3953) 1/29/2005 5:16:41 AM

On Fri, 28 Jan 2005 23:25:34 GMT, CBFalconer 
   <cbfalconer@yahoo.com> wrote:

> 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
0
Reply chris23 (644) 1/29/2005 12:05:55 PM

In article <41FAAFD9.551C745A@yahoo.com>, cbfalconer@yahoo.com says...
> 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?

-- 
Randy Howard (2reply remove FOOBAR)
0
Reply randyhoward (3272) 1/31/2005 5:45:50 AM

Randy Howard wrote:
> In article <41FAAFD9.551C745A@yahoo.com>, cbfalconer@yahoo.com says...
> 
>> 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?

There is that :-)  I never saw any need for a pdecl.

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


0
Reply cbfalconer (19183) 1/31/2005 1:00:05 PM

In article <slrncvmv13.5nv.chris@ccserver.keris.net>,
Chris Croughton  <chris@keristor.net> wrote:
....
>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

0
Reply gazelle (565) 4/14/2005 12:30:43 PM

gazelle@yin.interaccess.com (Kenny McCormack) wrote:

> In article <slrncvmv13.5nv.chris@ccserver.keris.net>,
> Chris Croughton  <chris@keristor.net> wrote:
> ...
> >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.

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
0
Reply rlb (4118) 4/14/2005 1:58:02 PM

On Thu, 14 Apr 2005 12:30:43 GMT, Kenny McCormack 
   <gazelle@yin.interaccess.com> wrote:

> In article <slrncvmv13.5nv.chris@ccserver.keris.net>,
> Chris Croughton  <chris@keristor.net> wrote:
> ...
>>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.

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
0
Reply chris23 (644) 4/14/2005 2:24:31 PM


Chris Croughton wrote:
> On Thu, 14 Apr 2005 12:30:43 GMT, Kenny McCormack 
>    <gazelle@yin.interaccess.com> wrote:
> 
> 
>>In article <slrncvmv13.5nv.chris@ccserver.keris.net>,
>>Chris Croughton  <chris@keristor.net> wrote:
>>...
>>
>>>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.
> 
> 
> 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.

-- 
Eric.Sosman@sun.com

0
Reply Eric.Sosman (4228) 4/14/2005 4:47:20 PM

Eric Sosman <eric.sosman@sun.com> spoke thus:

>     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 :-)

-- 
Christopher Benson-Manica  | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org    | don't, I need to know.  Flames welcome.
0
Reply ataru (1609) 4/14/2005 6:06:07 PM

gazelle@yin.interaccess.com (Kenny McCormack) writes:
[...]
> 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.

It depends on what you mean by "work".

In the real world, many things "work" well enough to pass testing,
only to break, probably at the most inconvenient possible time, in
actual use.

In the case of C code, the standard is a contract between the
programmer and the implementation.  If the programmer writes code that
happens to "work", but that violates the contract (e.g., by invoking
undefined behavior), the implementation, or a future one, is under no
obligation to make it continue to work.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
San Diego Supercomputer Center             <*>  <http://users.sdsc.edu/~kst>
We must do something.  This is something.  Therefore, we must do this.
0
Reply kst-u (21473) 4/14/2005 9:01:35 PM

Keith Thompson <kst-u@mib.org> writes:
> gazelle@yin.interaccess.com (Kenny McCormack) writes:
> [...]
>> 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.
>
> It depends on what you mean by "work".
>
> In the real world, many things "work" well enough to pass testing,
> only to break, probably at the most inconvenient possible time, in
> actual use.

A concrete example:

#include <stdio.h>
#include <string.h>
int main(void)
{
    char before[10];
    char message[10];
    char after[10];

    strcpy(message, "hello, world");
    printf("%s\n", message);
    return 0;
}

This "works".  Is it "right"?

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
San Diego Supercomputer Center             <*>  <http://users.sdsc.edu/~kst>
We must do something.  This is something.  Therefore, we must do this.
0
Reply kst-u (21473) 4/14/2005 9:19:20 PM

On Thu, 14 Apr 2005 12:47:20 -0400, Eric Sosman 
   <eric.sosman@sun.com> wrote:

> Chris Croughton wrote:
>> 
>> 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.

Be a lert, your country needs lerts!

Duh, I meant that he wanted me to write x << 1 instead of x * 2.  Which
in fact my error above illustrates why his "approved" code was less
maintainable, I can see the difference between x * 2 and x / 2 much more
easily than between x << 1 and x >> 1 (I have a slight and erratic
right-left aphasia, occasionally I will say one and mean the other --
"no, not that left, the /other/ left!").

Chris C
0
Reply chris23 (644) 4/14/2005 10:23:50 PM

22 Replies
40 Views

(page loaded in 0.253 seconds)

Similiar Articles:


















7/23/2012 2:45:10 AM


Reply: