imported txt file, display sorted ascending array.
Mar 21, 2022 at 9:32pm UTC
I am importing a txt file with 100 random type double numbers. I need to take the numbers place them in an array and sort them in ascending order. Lastly I need to export that data to a new txt file. I am stuck on the sorting part.
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
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("c:txtdoc.txt" , ios::in);
double inValue;
int size = 0;
bool fail = 0;
int j;
int n;
while (fail == 0)
{
myfile >> inValue;
fail = myfile.fail();
if (fail == 0)
{
size = size + 1;
}
}
myfile.clear();
myfile.seekg(0, ios::beg);
double * array1;
array1 = new double [size];
for (n = 0; n < size; n++)
{
for (j = n + 1; j < size; j++)
{
if (array1[n] > array1[j])
{
int temp = array1[n];
array1[n] = array1[j];
array1[j] = temp;
}
}
myfile >> array1[n];
}
for (int n = 0; n < size; n++)
{
cout << n << ", " << array1[n] << endl;
}
cout << endl;
system("pause" );
myfile.close();
return (0);
}
Mar 21, 2022 at 10:12pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<double > A;
ifstream in( "txtdoc.txt" );
for ( double value; in >> value; ) A.push_back( value );
sort( A.begin(), A.end() );
ofstream out( "output.txt" );
for ( double d : A ) out << d << '\n' ;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <fstream>
#include <set>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
ifstream in( "txtdoc.txt" );
multiset<double > S( istream_iterator<double >( in ), {} );
ofstream out( "output.txt" );
copy( S.begin(), S.end(), ostream_iterator<double >{ out, "\n" } );
}
Last edited on Mar 21, 2022 at 10:23pm UTC
Topic archived. No new replies allowed.