-
while not '\n'
suppose you will get the average of N numbers.
the input would just be the N numbers
e.g.
1 2 3 4
2.5
1 2 3 4 5
3
my problem is how to terminate when the enter is pressed.
Code:
while ( \* right code *\ != '\n' )
{
cin >> x;
ave+=x;
n++;
}
cout<< ave/n;
-
You should use std::getline for that:
getline - C++ Reference
First read a line, then parse it...
To be honest I consider this to be one great weakness in the C++ streams. I used to be a C coder, and I just never got the hang of those C++ streams, even though I know most of the stl....
-
theres 2 ways to do this that come to mind.
one of them involve stdio.h
(the main idea is that you know how many numbers (N) there are)
Code:
#include <stdio.h>
const int n = 5;
int main()
{
double avg;
for(int i=0;i<n;++i)
{
int input;
scanf("%d", &input);
avg+=input;
}
avg=avg/n;
printf("%f",avg);
return 0;
}
and
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
const int n = 5;
int main()
{
string input;
double avg;
getline(cin,input);
istringstream iss(input);
for(int i=0;i<n;++i)
{
int token;
iss >> token;
avg+=token;
}
avg = avg / n;
cout << avg;
return 0;
}
...now I guess if you dont know N before hand..
try this, im not 100% this is correct though
Code:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int n = 0;
string input;
double avg;
getline(cin,input);
istringstream iss(input);
int token;
while( iss >> token )
{
avg+=token;
++n;
}
avg = avg / n;
cout << avg;
return 0;
}
EDIT: i tried it, it works
-
@rodrigorules:
If you wouldn't have forgotten to initialize "avg" to 0 it would even be legal C++ code :P (I think, that's the only bug I can spot by just looking at it for a few seconds).