Array selectionsort issue and output - c++

Hello I am not sure what is wrong with my code.
Selection Sort works but when the program asks the user again to input a name, they don't get the correct person. Can someone help me? I'm not sure what is wrong.
EDIT: The error I am getting now for the second time I ask for input is "Name not found". I don't get why
Image is here:
http://i.imgur.com/2Gkd0gh.pngh
Here is my complete code:
#include <iomanip>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
// GLOBAL CONSTANTS
const int NUM_NAMES = 20;
// FUNCTION PROTOTYPES
void getNames(ifstream &, string[], int[], int);
int linearSearch(const string[], int, string);
int binarySearch(const string[], int, string);
void selectionSort(string[], int[], int);
void displayData(const string[], const int[], int);
void displaySearch(const string[], const int[], int);
int main()
{
// LOCAL VARIABLES
string names [NUM_NAMES];
int marks [NUM_NAMES];
ifstream inStream; // Input file stream variable
int index = 0;
string searchWho;
// FUNCTION CALL 1
getNames (inStream, names, marks, NUM_NAMES);
cout << endl;
cout << " Students and Marks:" << endl;
cout << " ______________________________" << endl << endl;
// FUNCTION CALL 2: DisplayData
displayData(names, marks, NUM_NAMES);
// OUTPUT - Perform search - USER INPUT
cout << endl;
cout << " Please enter the first and last name of who who want to look up, seperated with a space." << endl << endl;
cout << " "; cin >> searchWho;
cout << endl << endl;
// FUNCTION CALL 3: linearSearch
index = linearSearch (names, NUM_NAMES, searchWho);
// FUNCTION CALL 4: displaySearch
displaySearch(names, marks, index);
// FUNCTION CALL 5: selectionSort
selectionSort (names, marks, NUM_NAMES);
cout << endl;
cout << " Students and Marks:" << endl;
cout << " ______________________________" << endl << endl;
displayData(names, marks, NUM_NAMES);
// OUTPUT - Perform search - USER INPUT
cout << endl;
cout << " Please enter the first and last name of who who want to look up, seperated with a space." << endl << endl;
cout << " "; cin >> searchWho;
cout << endl << endl;
// FUNCTION CALL 4
index = binarySearch (names, NUM_NAMES, searchWho);
displaySearch(names, marks, index);
cout << " "; return 0;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION 1: getNames
// DESCRIPTION: Function opens data file students.txt
// Function reads data from students.txt and stores data
// appropriately according to customerCode and utilityCharge
// in parallel arrays Customer[] and Charge[]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void getNames (ifstream &inStream, string names[], int marks[], int numElts)
{
// Open input file
inStream.open ("students.txt");
string studentNames; // Student names - Last name followed by first
int studentMarks = 0; // Student mark for text/exam
// Read in data from students.txt
while (!inStream.eof())
{
for(int count = 0; count < numElts; count ++)
{
inStream >> names[count];
inStream >> marks[count];
}
}
inStream.close();
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION: LinearSearch
// DESCRIPTION:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int linearSearch (const string names[], int numElts, string who)
{
int index = 0; // Used as a subscript to search array
int position = -1; // To record position of search value
bool found = false; // Flag to indicate if value was found
while (index < numElts && !found)
{
if (names[index] == who) // If the name is found
{
found = true; // Set the flag
position = index; // Record the value's subscript
}
index++; // Go to the next element
}
return position; // Return the position, or -1
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// FUNCTION: SelectionSort
// DESCRIPTION:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void selectionSort(string names[], int marks[], int numElts)
{
int startScan;
int minIndex;
int startName;
for (startScan = 0; startScan < (numElts - 1); startScan++)
{
startName = startScan;
for (int minIndex = startScan + 1; minIndex < numElts; minIndex++)
{
if (names[minIndex] > names[startName])
{
startName = minIndex;
string tempString = names[startScan];
names[startScan] = names[minIndex];
names[minIndex] = tempString;
// Aligning arrays
int tempInt = marks[startScan];
marks[startScan] = marks[minIndex];
marks[minIndex] = tempInt;
}
}
}
}
int binarySearch(const string names[], int numElts, string who)
{
int first = 0; // First array element
int last = numElts - 1; // Last array element
int middle; // Mid point of search
int position = -1; // Position of search value
bool found = false; // Flag
while (!found && first <= last)
{
middle = (first + last) / 2; // Calculate mid point
if (names[middle] == who) // If value is found at mid
{
found = true;
position = middle;
}
else if (names[middle] > who) // If value is in lower half
{
last = middle - 1;
}
else
{
first = middle + 1; // If value is in upper half
}
}
return position;
}
void displayData(const string names[], const int marks[], int numElts)
{
// OUTPUT
for (int count = 0; count < numElts; count++)
{
cout << " " << left << setw(15) << names[count] << right << setw(15) << marks[count] << endl;
}
}
void displaySearch(const string names[], const int marks[], int index)
{
if (index == -1)
{
cout << " Name not found. Restart the program to search again." << endl << endl;
}
else
{
cout << names[index] << " scored " << marks[index] << " marks." << endl << endl;
}
}

From the shared image http://i.imgur.com/2Gkd0gh.pngh, the array is not properly sorted. For examples,
Allison,Jeff 45
Collins,Bill 80
Allen,Jim 82
As in the code belows:
if (names[minIndex] > names[startName])
{
startName = minIndex;
//...
}
startName means the index of the max name in names array, doesn't it? (the array is descendingly sorted, right?)
So it supposes to be to swap the max name at index startName with the current scanning name at index startScan. Then it should be
startName = startScan;
for (int minIndex = startScan + 1; minIndex < numElts; minIndex++)
{
if (names[minIndex] > names[startName])
{
startName = minIndex;
}
}
string tempString = names[startScan];
names[startScan] = names[startName];
names[startName] = tempString;
// Aligning arrays
int tempInt = marks[startScan];
marks[startScan] = marks[startName];
marks[startName] = tempInt;
And in the binarySearch, it supposes the array is in ascending order.
Therefore, to sort the array in ascending order, you may change
if (names[minIndex] > names[startName])
{
startName = minIndex;
}
to
if (names[minIndex] < names[startName])
{
startName = minIndex;
}

Related

C++ programming define array size from the external text file

I am trying to make my array have a size of a non-constant value. The size should be defined by the "test.txt" file that gets the information from. For example, if the txt file has 10 numbers then the array should be in size of 10. I tried using vectors but I couldn't make it work. Any help would be much appreciated. Here is the code below:
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
#include<cstdlib>
using namespace std;
/* Function to print an array
A int[]: an array of n element
n int; length of an array
*/
void displayList(float A[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << A[i] << ", ";
cout << endl;
}
/*
Insertion Sort function
A int[]: an array of n element
n int; length of an array
*/
void insertionSort(float A[], int n)
{
int i, j;
float key;
for (i = 1; i < n; i++)
{
key = A[i];// take key
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && A[j] > key)
{
A[j + 1] = A[j]; // move element to next postion
j = j - 1; // reduce index of j - go backward in the array
}
std::cout << "Step key at i = " << i << ": [" << key << "] inserted at j = " << j + 1 << "
position -> ";
A[j + 1] = key; // at j+1 th position we place the key
displayList(A, n);
}
};
ifstream input("test.txt"); //put your program together with thsi file in the same folder.
int main() {
int const ARRAY_SIZE = 9;
float A[ARRAY_SIZE];
string line;
ifstream inFile;
int i = 0, cnt = 0;
float n;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (!inFile.eof()) {
getline(inFile, line);
n = atof(line.c_str());
cnt++;
}
int cnt;
cin >> cnt;
vector<float> A(cnt);
inFile.close();
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (!inFile.eof()) {
getline(inFile, line);
n = atof(line.c_str());
A[cnt++] = n;
}
inFile.close();
n = sizeof(A) / sizeof(A[0]);
cout << "insertionSort: \n";
cout << "Unsorted array: ";
displayList(A, n);
insertionSort(A, n);
std::cout << "Sorted array: ";
displayList(A, n);
}
sample input from txt file:
12
4
5
9
6
11
0
2
0.5
To make it work with vectors you shouldn't create the vector with a number of elements, like vector<float> v(10);. Create an empty vector and add one value at a time to it.
void display(const std::vector<float>& A) {
std::cout << "Got " << A.size() << " elements.\n";
for(float value : A) {
std::cout << value << '\n';
}
}
int main() {
std::vector<float> A; // an empty vector of floats
float temp; // a temporary float to use for extraction
while(input >> temp) { // loop while extraction succeeds
A.push_back(temp); // save the value at the end of the vector
}
display(A);
}

Unable to print the reverse of a user-filled partial array

For an assignment, we were to fill an array with user-defined characters that stops filling once the user enters a full stop ".". Part of the assignment is to print out the characters entered in the array in reverse, but what I have seems to just print nothing.
First time asking, so apologies if it's a silly question. Thanks in advance.
#include <iostream>
using namespace std;
//Function declarations
bool fillArray(char charArray[], int arraySize, int& numberUsed);
void outputInReverse(const char charArray[], int& numberUsed);
int main() {
const int arraySize = 100;
char charArray[arraySize] = { };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
}
//Function definitions
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
charArray[index] = inputChar;
//How many entries made
numberUsed = i;
count++;
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count - 1) << endl;
return count;
}
}
}
if (numberUsed == arraySize) {
arrayFull = true;
return arrayFull;
}
return sentinelEntered;
return count;
}
// Reverse
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed; i > 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}
FILLING ARRAY....
Enter up to 100 character values. Enter full stop to end. Enter char 1:
a
Enter up to 100 character values. Enter full stop to end. Enter char 2:
b
Enter up to 100 character values. Enter full stop to end. Enter char 3:
c
Enter up to 100 character values. Enter full stop to end. Enter char 4:
d
Enter up to 100 character values. Enter full stop to end. Enter char 5:
e
Enter up to 100 character values. Enter full stop to end. Enter char 6:
.
Number of entries: 5
ARRAY OUTPUT....
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Output in reverse:
Not sure what you are trying to return from fillArray(), but since its a bool type, assuming you are trying to return if the array is empty or not. Observe added comments to see corrections.
int main() {
const int arraySize = 100;
//corrected
char charArray[arraySize] = { NULL };
int numberUsed = 0;
//Function calls
cout << "\nFILLING ARRAY....\n";
fillArray(charArray, arraySize, numberUsed);
cout << "\nARRAY OUTPUT....\n";
outputInReverse(charArray, numberUsed);
return 0;
}
bool fillArray(char charArray[], int arraySize, int& numberUsed) {
char inputChar;
int index = 0;
const char sentinel = '.';
bool sentinelEntered = false;
bool arrayFull = false;
int count = 0;
//Take user input
for (int i = 0; i < arraySize; i++) {
if ((!sentinelEntered)) {
cout << "Enter up to " << arraySize << " character values. Enter full stop to
end. " << "Enter char " << (i + 1) << ": " << endl;
cin >> inputChar;
//corrected: shifted here so before '.' can enter into array we return
if ((inputChar == sentinel)) {
sentinelEntered = true;
cout << "Number of entries: " << (count) << endl;
//correction: update numberUsed before returning and no of
//elements = count
numberUsed = i;
return count;
}
//correction: array index should not be "index" but i
charArray[i] = inputChar;
//How many entries made
numberUsed = i;
count++;
}
}
if (numberUsed == arraySize)
return true;
return false;
}
void outputInReverse(const char charArray[], int& numberUsed) {
for (int i = numberUsed-1; i >= 0; i--) {
cout << "Output in reverse: " << charArray[i] << endl;
}
}

Organizing names by last name with three of the same surnames (C++)?

I have an assignment to sort a list of names alphabetically by last name. However, there are three names with the same surname and I can't get the first names to alphabetize with the surnames. Have to code own bubble sort or other sorting algorithm. I chose bubblesort because it's one of the only ones we've learned so far. Any help is appreciated. Everything works except the correct assortment.
Here is my code:
// my name
// Program 6
// This program will show a list of names in a variety of orders.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int size = 25;
void showContacts_FNLN(string fnameArray[], string lnameArray[], int size);
void showContacts_LNFN(string lnameArray[], string fnameArray[], int size);
void reverseContacts_FNLN(string fnameArray[], string lnameArray[], int size);
void reverseContacts_LNFN(string fnameArray[], string lnameArray[], int size);
void searchLasname(string lnameArray[], string fnameArray[], int size);
void searchFirname(string fnameArray[], string lnameArray[], int size);
void bubbleSort(string lnameArray[], string fnameArray[], int size);
int main(int argc, const char * argv[])
{
int count = 0;
int ans;
ifstream nameData;
string lnameArray[size];
string fnameArray[size];
string lname, fname;
nameData.open("names.txt");
while(nameData >> fname >> lname)
{
fnameArray[count] = fname;
lnameArray[count] = lname;
count ++;
}
bubbleSort(lnameArray, fnameArray, size);
while(ans != 9)
{
cout << "What would you like to do?" << endl;
cout << "1) display contacts by first name and last name" << endl;
cout << "2) display contacts by last name and first name" << endl;
cout << "3) display contacts by first name and last name in reverse order" << endl;
cout << "4) display contacts by last name and first name in reverse order" << endl;
cout << "5) search for contact by last name" << endl;
cout << "6) search for contact by first name" << endl;
cout << "9) exit" << endl;
cout << "Enter: ";
cin >> ans;
cout << endl;
switch(ans)
{
case 1: showContacts_FNLN(fnameArray, lnameArray, size); // shows contacts in FN-LN order
break;
case 2: showContacts_LNFN(lnameArray, fnameArray, size); // LN-FN order
break;
case 3: reverseContacts_FNLN(fnameArray, lnameArray, size); // reversed FN-LN order
break;
case 4: reverseContacts_LNFN (fnameArray, lnameArray, size); // reversed LN-FN order
break;
case 5: searchLasname(lnameArray, fnameArray, size); // searches based on LN
break;
case 6: searchFirname(fnameArray, lnameArray, size); // searches based on FN
break;
case 9: cout << "Goodbye!" << endl;
break;
}
}
nameData.close();
return 0;
}
void showContacts_FNLN(string fnameArray[], string lnameArray[], int size)
{
for(int i=0; i<size; i++)
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
}
cout << endl;
}
void showContacts_LNFN(string lnameArray[], string fnameArray[], int size)
{
for(int i=0; i<size; i++)
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
}
cout << endl;
}
void reverseContacts_FNLN(string fnameArray[], string lnameArray[], int size)
{
for(int i=(size-1); i>=0; i--)
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
}
cout << endl;
}
void reverseContacts_LNFN(string fnameArray[], string lnameArray[], int size)
{
for(int i=(size-1); i>=0; i--)
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
}
cout << endl;
}
void searchLasname(string lnameArray[], string fnameArray[], int size)
{
int c = 0;
string slnam;
cout << "Enter a last name: ";
cin >> slnam;
for(int i=0; i<size; i++)
{
if(slnam==lnameArray[i])
{
cout << lnameArray[i] << ", " << fnameArray[i] << endl;
c++;
}
}
if (c == 0)
{
cout << "There is no match.";
cout << endl;
}
cout << endl;
}
void searchFirname(string fnameArray[], string lnameArray[], int size)
{
int c = 0;
string sfnam;
cout << "Enter a first name: ";
cin >> sfnam;
for(int i=0; i<size; i++)
{
if(sfnam==fnameArray[i])
{
cout << fnameArray[i] << " " << lnameArray[i] << endl;
c++;
}
}
if (c==0)
{
cout << "There is no match." << endl;
}
cout << endl;
}
void bubbleSort(string lnameArray[], string fnameArray[], int size)
{
string tmp, tmp2;
//int count=0;
for( int i = 1; i <= size - 1; i++ )
{
for( int j = 0; j < size - i; j++ )
{
//count++;
if( lnameArray[j] > lnameArray[j+1] )
{
tmp = lnameArray[j];
lnameArray[j] = lnameArray[j+1];
lnameArray[j+1] = tmp;
}
if(lnameArray[j] == lnameArray[j+1])
{
if(fnameArray[j] > fnameArray[j+1])
{
tmp = lnameArray[j];
lnameArray[j] = lnameArray[j+1];
lnameArray[j+1] = tmp;
tmp2 = fnameArray[j];
fnameArray[j] = fnameArray[j+1];
fnameArray[j+1] = tmp2;
}
}
}
}
//cout << "count = " << count << endl;
}
Here you go:
void bubbleSort(string lnameArray[], string fnameArray[], int size)
{
for( int i = 0; i < size - 1; i++ )
{
for( int j = 0; j < size - i - 1; j++ )
{
string name1 = lnameArray[j] + fnameArray[j];
string name2 = lnameArray[j + 1] + fnameArray[j + 1];
if(name1.compare(name2) > 0)
{
string tmp = lnameArray[j];
lnameArray[j] = lnameArray[j + 1];
lnameArray[j + 1] = tmp;
tmp = fnameArray[j];
fnameArray[j] = fnameArray[j + 1];
fnameArray[j + 1] = tmp;
}
}
}
}
Instead of having another 'if' for those that have similar last names, I combined the last name and the first name instead then used it for comparison.
I also noticed in your code in for( int j = 0; j < size - i; j++ ) that you forgot to add - 1 after size - i. Once j == size - i - 1 (assuming that i == 0 currently) then you use j + 1 to access an index, this will cause a segmentation fault since you're accessing an index beyond its range.
Your sort doesn't work because you change the position of the last names only (except for the case where two last names are equal.)
You should use a struct to store this information together in one array. Then you can simplify your code a lot:
struct Person {
Person() = default;
Person(string firstname, string lastname) : firstname(std::move(firstname)), lastname(std::move(lastname)) {}
string firstname;
string lastname;
};
void showContacts_FNLN(Person personArray[], int size) {
for (int i = 0; i < size; i++) {
cout << personArray[i].firstname << " " << personArray[i].lastname << endl;
}
cout << endl;
}
void bubbleSort(Person personArray[], int size) {
for (int i = 1; i <= size - 1; i++) {
// The condition must size - i - 1 because otherwise personArray[j+1] is faulty
for (int j = 0; j < size - i - 1; j++) {
if (personArray[j].lastname > personArray[j+1].lastname
|| (personArray[j].lastname == personArray[j+1].lastname &&
personArray[j].firstname > personArray[j+1].firstname)) {
auto tmp = std::move(personArray[j]);
personArray[j] = std::move(personArray[j+1]);
personArray[j+1] = std::move(tmp);
}
}
}
}
int main(int argc, const char * argv[]) {
int count = 0;
ifstream nameData;
Person personArray[size];
string lname, fname;
nameData.open("names.txt");
while(nameData >> fname >> lname) {
personArray[count] = Person(fname, lname);
count++;
}
nameData.close();
bubbleSort(personArray, size);
showContacts_FNLN(personArray, size);
return 0;
}
I removed some non-essential parts from this example to keep it very short but you should get the idea. (Note that my code makes use of C++11 move semantics, if this confuses you, just remove them.)
Some more suggestions:
Do not use using namespace std;. (The internet will tell you why.)
If you can, use std::array, which eliminates the need to always pass the size of the arrays and allows you to use a C++11 range for loop.

Array search and unique value addition

(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}

c++ arrays and functions and counters

My code is done and working. But i cant figure out how to count the number of attempts made by the user and invalid account numbers that were entered. I am supposed to do this in main starting after cin >> accountNum. After the user enters 9999 to quit, it is supposed to display the number of attempts made and the number of invalid charge account numbers that were entered. When i run it i get 0 for number of attempts and -1 for invalid numbers entered.
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void getAccountNumbers(int[], int);
void displayAccountNumbers(int[], int);
void selectionSort(int[], int);
int binarySearch(const int[], int, int);
int main()
{
int accountNum;
int results;
int attempts = 0;
int invalidNumbers = 0;
const int ARRAY_SIZE = 18; // Array size
int numbers[ARRAY_SIZE]; // Array with 18 elements
int count = 0;
//ifstream inputFile;
getAccountNumbers(numbers, ARRAY_SIZE);
cout << "Original Order" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
selectionSort(numbers, ARRAY_SIZE);
cout << "Sorted List" << endl;
displayAccountNumbers(numbers, ARRAY_SIZE);
cout << "********************" << endl;
cout << "Enter an Account number or 9999 to quit" << endl;
cin >> accountNum;
if(accountNum == 9999)
{
cout << "Thank You!" << endl;
}
while(accountNum != 9999)
{
results = binarySearch(numbers, ARRAY_SIZE, accountNum);
if(results == -1)
{
cout << "That number was not found" << endl;
invalidNumbers = results++;
}
else
{
cout << "That number is valid " << endl;
}
attempts = results++;
cin >> accountNum;
}
cout << "Number of attempts: " << attempts << endl;
cout << "Invalid numbers entered: " << invalidNumbers << endl;
system("pause");
return 0;
}
void getAccountNumbers(int nums[], int size)
{
ifstream inputFile;
int count = 0;
//Open the file
inputFile.open("charges.txt");
while(count < size && inputFile >> nums[count])
count ++;
//Close the file
inputFile.close();
}
void displayAccountNumbers(int nums[], int size)
{
for(int count = 0; count < size; count++)
cout << nums[count] << "\t";
cout << endl << endl;
}
void selectionSort(int nums[], int size)
{
int startScan, minIndex, minValue;
for(startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minValue = nums[startScan];
for(int index = startScan + 1; index < size; index++)
{
if(nums[index] < minValue)
{
minValue = nums[index];
minIndex = index;
}
}
nums[minIndex] = nums[startScan];
nums[startScan] = minValue;
}
}
int binarySearch(const int nums[], int size, int value)
{
int first = 0, //First element
last = size - 1, // Last element
middle, // Midpoint
position = -1; //Position of search value
bool found = false;
while(!found && first <= last)
{
middle = (first + last) / 2; //Midpoint
if(nums[middle] == value)
{
found = true;
position = middle;
}
else if(nums[middle] > value) // Value is in lower half
last = middle - 1;
else
first = middle + 1; // Value is in upper half
}
return position;
}
Your problem is in the lines where you are trying to add to invalidNumbers and attempts. The ++ postfix operator adds one to the number before it. You needn't say invalidNumbers = results++;; you merely need invalidNumbers++;, and the same applies for attempts. What your code was doing was setting invalidNumbers (and attempts) to the value of results and then adding one to results instead.