c++ - Sorting data from text file -
i need write program reads unknown number of numerical data text file array , uses sorting parameter sort numbers. i've been trying hours , can't program work
void sort(double &, double arr[], int s); int main() { fstream myfile; int size, = 0; const int n = 1000; double x[n]; //reading data myfile.open("data.txt"); if (myfile.fail()) { cout << "error opening file" << endl; exit(1); } while (!myfile.eof()) { myfile >> x[i]; cout << x[i] << endl; i++; } size = - 1; cout << size << " number of values in file" << endl; myfile.close(); = 0; while (size > i) { cout << x[i] << endl; i++; } //sorting sort(x[n], x[n], size); = 0; while (size > i) { cout << x[i] << endl; i++; } return 0; } void sort(double &, double arr[], int s) { bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; (int = 0; < s - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; &[i + 1] = &tmp; swapped = true; } } } }
while (!myfile.eof())
is wrong, why iostream::eof inside loop condition considered wrong? end reading end of file. use instead
while (myfile >> x[i])
in case, can declare x
std::vector
, like
std::vector<double> x;
read content vector, use
std::sort(x.begin(), x.end());
nothing more simple.
and complete c++ standard library solution, can use iterators , sorting algorithms, like
#include <algorithm> #include <iostream> #include <fstream> #include <iterator> #include <vector> int main() { std::fstream myfile("data.txt"); // should test if it's open correctly std::vector<double> x(std::istream_iterator<double>(myfile), {}); std::sort(x.begin(), x.end()); for(const auto& elem: x) std::cout << elem << " "; }
you can map code above function. have no idea mean sorting parameter. if need able sort ascending/descending, may use std::less
or std::greater
(need #include <functional>
), third parameter std::sort
, like
std::sort(x.begin(), x.end(), std::greater<double>()); // sorts in descending order
or write own comparator functor/lambda function.
Comments
Post a Comment