C++ problem with strings

Hello, I want to know how to split a string in C++.

In fact i want to do a program that do that:
Write a program that reads a sequence of numbers and prints their average.

Input

Input consists of a non-empty sequence of strictly positive real numbers.

Output

Print the average of the numbers with 2 digits after the decimal point.

"EXAMPLES"

Input

1 4 9

Output

4.67

Input

7.4

Output

7.40


But I don't know how to split the input and then do the average.
Thanks.
One way to do it:
1
2
3
4
5
6
7
8
9
  double num = 0;
  string input;
  getline (cin, input); 
  istringstream iss (input);

  while (iss >> num)
  {
    //TODO do sth. with num here.
  }
first you will divide the no. with its form like 149 it is 9 is one 4 is in 10 and 1in 100 position then plus all and do what you want
Thanks Thomas1965, it works well. The problem is that I don't now how "isdtringstream iss" works :(, but doing that the program works perfect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <math.h>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
int main(){
  double num = 0;
  string input;
  getline (cin, input); 
  istringstream iss (input);
  double a;
  double i = 0;
  while (iss >> num)
  {
    //TODO do sth. with num here.
    i ++;
    a = (a+num);
  }
  a = a/i;
  cout << a << endl;
  fflush(stdin);
}
istringstream works like cin, the difference is that the input comes from a string instead of keyboard.
Topic archived. No new replies allowed.