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
|
#include <iostream>
#include <fstream>
using namespace std;
// function prototypes
int binarySearch(const int [], int, int);
void selectionSort(int[], int);
void swap(int &, int &);
const int SIZE = 200;
int main()
{
const int ARRAY_SIZE = 200; // Array size
int numbers[ARRAY_SIZE]; // array with 200 elements
int count = 0; // Loop counter variable
ifstream inputFile; // Input file
string name, filename;
int number;
int values[ARRAY_SIZE] = {};
std::string fileNames[]
{
"numbers.txt",
"File2.txt",
"File3.txt"
};
std::cout << "\nFile names available:\n";
for (int idx = 0; idx < sizeof(fileNames)/sizeof(fileNames[0]); idx++)
{
std::cout << ' ' << fileNames[idx] << '\n';
}
// prompt user to enter file name. also display if it exists or not
// Get file name from the user
cout << "\nEnter the file name: ";
cin >> filename;
// open the file
inputFile.open(filename);
if (inputFile)
{
// Read the numbers from the file and display them.
while (count < ARRAY_SIZE && inputFile >> numbers[count])
count ++;
{
cout << number << endl;
}
// close the file.
inputFile.close();
}
else
{
// Display an error message.
cout << "Error opening the file.\n";
}
// display the numbers read:
cout << "The numbers are: ";
for (count = 0; count < ARRAY_SIZE; count++)
cout << numbers[count] << " ";
cout << endl;
// sort the array
selectionSort(values, ARRAY_SIZE);
// Display the sorted array.
cout << "The sorted values:\n";
for (auto element : values)
cout << element << " ";
cout << endl;
return 0;
}
void selectionSort(int array[], int size)
{
int minIndex, minValue;
for (int start = 0; start < (size - 1); start++)
{
minIndex = start;
minValue = array[start];
for (int index = start + 1; index < size; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
}
swap(array[minIndex], array[start]);
}
}
//***************************************************
// The swap function swaps a and b in memory. *
//***************************************************
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
|