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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
|
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<new>
using namespace std ;
bool OpenFile(ifstream &) ;
void ReadFile(ifstream &, float [], int) ;
void Print(float [], int) ;
int CalcSize(ifstream &) ;
void BubbleSort(float [], int) ;
int main()
{
ifstream fin ;
float * dArray = NULL;
int size ;
size = CalcSize(fin) ;
dArray = new (nothrow) float[size] () ;
if(dArray == 0)
cout << "Error: memory could not be allocated." ;
else
{
ReadFile(fin, dArray, size) ;
Print(dArray, size) ;
delete [] dArray ;
dArray = NULL ;
}
} // end Function main
bool OpenFile(ifstream &fin)
{
string inputFile ;
int opentrys = 3 ;
cout << endl << "Please enter the name of the input file: " ;
getline(cin, inputFile) ;
fin.open(inputFile.c_str()) ;
if (fin.fail())
{
while (fin.fail())
{
if (opentrys == 0)
{
cout << endl << "0 attempts remaining. Please try again later." << endl << endl ;
return false ;
exit(1) ;
}
cout << endl << "You inputted a bad file name. (" << opentrys << " attempts remaining)" << endl ;
cout << "Please enter the name of the input file: " ;
cin >> inputFile ;
fin.open(inputFile.c_str()) ;
opentrys-- ;
} // While loop
return true ;
} // If statement
else
return true ;
} // end Function OpenFile
int CalcSize(ifstream & fin)
{
int x ;
int counter = 1 ;
if(OpenFile(fin))
{
fin >> x ;
if(fin.eof())
{
cout << endl << "The file was empty." ;
exit(1) ;
}
while(!fin.eof())
{
counter++ ;
fin >> x ;
}
}
return counter ;
} // end Function CalcSize
void ReadFile(ifstream & fin, float data[], int size)
{
int i = 0 ;
fin >> data[i] ;
while(!fin.eof())
{
fin.ignore(10, '\n') ;
fin >> data[++i] ;
} // While Loop
} // end Function ReadFile
void Print(float data[], int size)
{
BubbleSort(data, size) ;
cout << endl << "The file contains the following numbers: " ;
for(int i = 0; i < size-1; i++)
cout << data[i] << ", " ;
cout << data[size-1] << "." << endl << endl ;
}
void BubbleSort(float list[], int size)
{
int temp ;
bool flag ;
do
{
flag = false ;
size-- ;
for (int i=0; i<size; i++)
if (list[i] > list[i+1])
{
temp = list[i] ;
list[i] = list[i+1];
list[i+1] = temp ;
flag = true ;
}
} while (flag) ;
} // end Function BubbleSort
|