sum of all?

Nov 29, 2011 at 7:23pm
how to get some numbers in input in one line (we dont know how many are they),and print sum of all? just hint to do it
example
input:
3 4 5 6 7 8

output:
33
Last edited on Nov 29, 2011 at 7:55pm
Nov 29, 2011 at 7:34pm
Make a variable called "sum".

Read in each number one at a time. Add it to "sum".

When there are no more numbers, "sum" holds the sum of all the numbers.

Print it out using std::cout
Nov 29, 2011 at 7:41pm
what about input? how to write end of input?
Nov 29, 2011 at 7:47pm
You don't need to write the end of the input. When there is no more input, it's ended.
Nov 29, 2011 at 7:54pm
you mean like this ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
    long i,a[1000],sum=0,n;

    for(i=0;i<n;i++)
    {cin>>a[i];
        sum=sum+a[i];
    }
    cout<<sum;


    return 0;
}
Nov 29, 2011 at 8:05pm
closed account (GADSLyTq)
The way your current code is setup does not match what you told us. What you're doing is inputting the values one at a time. You stated that the numbers needed to be in one line. Are you reading the numbers from a external file or from the terminal?
Nov 29, 2011 at 8:10pm
i mean, user enter some numbers in one line and get sum of all? of course that code isn't true,but i just tried to understand what Moschops said
Nov 29, 2011 at 8:22pm

1
2
3
4
5
std::string inputLine;
getline(cin, line);

// Now read the characters. Each time you get to a space, turn the characters you read into a number,
//   add them to the sum, and then carry on 


Nov 29, 2011 at 8:52pm
i write like this to check if it read correctly or not unfotunately it doesn't work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{long i;
  string a;
  getline(cin,a);

for(i=0;i<4;i++)
{
    cout<<a[i];
}
return 0;
}
Last edited on Nov 29, 2011 at 8:52pm
Nov 29, 2011 at 9:33pm
closed account (GADSLyTq)
You must get the size of the string. In order to print the string correctly.

http://www.cplusplus.com/reference/string/string/size/
Last edited on Nov 29, 2011 at 9:33pm
Nov 29, 2011 at 10:37pm
I think the best way would be to use stringstream. Pass the string you got from getline to the stringstream constructor. Then just use operator >> until the stream is empty.
Topic archived. No new replies allowed.