Problem with cin

Hi, I was trying to make a program that calculates the arithmetic average of all the inputed numbers. The program works but there's one problem. I don't know how to tell the program to output the result because there are no more inputed numbers. Any ideas ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main () {
  
  cout.setf(ios::fixed);
  cout.precision(2);
  double n;
  double suma = 0;
  int d = 0 ;
  double mitjana;
  
  while (cin>>n) {
      suma= suma + n;
    ++d;
}
  mitjana = suma/d;
  cout << mitjana << endl;
}
    
Choose one:
1) Manually send end of stream by pressing Ctrl+D (Linux) or Ctrl+Z (Windows)
2) Enter a non-number
3) select a number to act as sntiel and stop input when it is entered
Last edited on
Thanks for your reply!
I already noticed that when I entered a non number I obtained the output. But what I was trying to say ( sorry I didn't express myself clearly in the last post) is if there's any way that if I input in a single line a bunch of numbers separated by a space, example: 23 65 78 23 , when I press return the program gives me the output.

Yes: use stringstream and getline:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

int main()
{
    std::cout << std::fixed << std::setprecision(2);
    std::string line;
    std::getline(std::cin, line);
    std::istringstream input(line);
    double sum = 0;
    int num = 0;
    double n;
    while(input >> n) {
        sum += n;
        ++num;
    }
    double avg = sum/num;
    std::cout << avg << '\n';
}
Input:
2 4.5 7
3 //should not be included in calculations

Output:
4.50
http://ideone.com/3NXnk4
Topic archived. No new replies allowed.