The correct program is:
#include <stdafx.h>
#include <stdio.h>
#include <fstream>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
//prototypes
void sortAcctNums(int accounts[], size_t count);
int findAcctNum(int accounts[], int numElems, int accountNumSearched);
//main part of the program. This is where all the magic happens
int main(){
string fileName;
int accountNumSearched, count = 0;
const int arraySize = 18;
int accounts[arraySize];
int location;
fstream inputFile(fileName, ios::in);
cout << "What is the filename of account numbers? ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()){//makes sure the file is able to be read, if not then requests user to try again
cout << "What is the account number you are looking for? ";
cin >> accountNumSearched;
while (inputFile >> accounts[count]){
count++;//populates the array
}
inputFile.close();//closes the file stream
sortAcctNums(accounts, sizeof(accounts)/sizeof(*accounts));//sorts the account numbers
location = findAcctNum(accounts, count, accountNumSearched);//assigns the value of the fundAcctNum function to location
if (location == -1){
cout << "The account number could not be found" << endl;
exit;
}
else
cout << "The account number you were looking for is: " << accounts[location] << endl
}
else
cout << "Error opening file. Please try again. " << endl;
return 0;
}
//this function sorts the account numbers with a bubble sort algorithm
void sortAcctNums(int accounts[], size_t count){
bool swap = true;
int temp;
while (count-- && swap){
swap = false;
for (size_t i = 0; i < count; ++i){
if (accounts[i] > accounts[i + 1]){
std::iter_swap(accounts + i, accounts + i + 1);
swap = true;
}
}
}
}
//This function searches the sorted array for the specified account number with a Binary search algorithm
int findAcctNum(int accounts[], int numElems, int accountNumSearched){
int first = 0,
last = numElems - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last){
middle = (first + last) / 2;
if (accounts[middle] == accountNumSearched){
found = true;
position = middle;
}
else if (accounts[middle] > accountNumSearched)
last = middle - 1;
else
first = middle + 1;
}
return position;
}//end search