Help with vectors?
My program needs to read values from a file into a vector and output which are medians. However, I am not getting any output. Any idea what's wrong?
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
void doCalculation ( istream & infile )
{
vector<double> median;
if (infile)
{
double value;
// read the elements in the file into a vector
while ( infile >> value )
{
median.push_back( value );
}
}
vector<double>::iterator i, j;
unsigned int smaller = 0, larger = 0;
// compare each value in the vector to each other
for ( i = median.begin(); i < median.end(); i++ )
{
for ( j = median.begin(); j < median.end(); j++ )
{
if ( *i > *j )
smaller++;
else
larger++;
}
if ( 2*smaller <= median.size() && 2*larger <= median.size() )
cout << *i << " is a median." << endl;
}
}
int main()
{
string filename;
cout << "Enter the name of the file ('end' to quit): " << endl;
cin >> filename;
while ( filename != "end" )
{
ifstream infile ( filename );
if ( infile )
{
doCalculation ( infile );
}
else
{
cout << filename << " failed to open" << endl;
}
cout << endl << "Enter the name of the file ('end' to quit): " << endl;
cin >> filename;
}
return 0;
}
|
Okay I'm pretty sure my error is that I'm not clearing smaller and larger after each loop. How do I do that?
Topic archived. No new replies allowed.