sum of all?

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
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
what about input? how to write end of input?
You don't need to write the end of the input. When there is no more input, it's ended.
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;
}
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?
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

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 


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