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 22 4031
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);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,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)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
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?
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[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
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.
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
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.c om, 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
Ben Pfaff <bl*@cs.stanfor d.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
Ben Pfaff wrote: Ben Pfaff <bl*@cs.stanfor d.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.c om, 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
CBFalconer <cb********@yah oo.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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: a |
last post by:
(I've reached that familiar place where I've got a nagging little
problem in a program I'm writing but I've been staring at code for too
long and I probably wouldn't be able to recognize the answer even if I
was staring right at it.)
I'm trying to design a function that reads input from my data file into
(a pair of) arrays. Simple enough? However, each line of the file is
either going to be 4 integers or a character (then a carriage...
|
by: agent349 |
last post by:
Hi,
I'm fairly new to c++. I need user input in the form of dollar
amounts, ie: "$10.00". I'd like to remove the dollar sign "$" then
store the rest in a variable. How do I go about removing the dollar
sign? Thanks in advance!
|
by: Hulo |
last post by:
In a C program I am required to enter three numbers (integers) e.g. 256
7 5 on execution of the program.
C:\> 256 7 5
There should be spaces between the three numbers and on pressing
"enter", further processing is done. The problem requires me to check
whether three numbers have actually been entered in the input line and
to warn if less or more numbers have been entered.
|
by: moostafa |
last post by:
Hi,
I'm writing a program that performs arithmetic operations on integers.
I want to be able to type in a bunch of integers seperated by any
amount of white space then terminate input with a non-integer
character. I plan to put my input into an array, and while I have a max
size I don't have a min and don't know exactly how many arguments to
expect.
I would really appreciate any ideas.
Cheers.
|
by: sam |
last post by:
hi all,
i'm starting to put together a program to simulate the performance of
an investment portfolio in a monte carlo manner doing x thousand
iterations and extracting data from the results.
i'm still in the early stages, and am trying to code something simple
and interactive to get the percentages of the portfolio in the five
different investment categories. i thought i'd get in with the error
handling early so if someone types in...
| |
by: Kavya |
last post by:
I saw these two ways for validating input
First Way
--------------
#include <iostream>
#include <limits>
using namespace std;
int main() {
|
by: powerej |
last post by:
writing a program that asks how many numbers the users want to enter, then input an integer for the amount of numbers said, output: number of integers entered, sum of them, average of them, maximum value entered and min value entered. the min is where i am having a problem i can get everything else to print out but i am doing something wrong in my while loop can someone please help me.
import javax.swing.*; // gets option pane
...
|
by: n3o |
last post by:
Hello Comp.Lang.C Members,
I have an issue with user input that I have been trying to figure out
for the longest. For instance, let's say you have something like this:
void foo()
{
int num;
printf("Please enter a number: ");
scanf("%d", &num); // yes I know this function may throw a
|
by: manxie |
last post by:
Dear All Readers,
I'm supposed to create a program with a switch and using voids to execute number of codes, that includes finding sum, average, maximum, and minimum, please read my code:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void WELCOME();
|
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...
|
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,...
| |
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...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |