Hi all,
I'm having a heck of a time with our latest assignment. I've tried everything I can possibly think if to make this work, but with no luck. We need to Load an inventory text file, sort it, search it(haven't even got to that portion of the code). I can't seem to get my insertion sort to work properly. I can get it to sort the item number, which is an int array named items. I cannot get it to sort the corresponding item names though. Also, for some reason when it loads the text file, it prints out the last line of the file twice. Anyone who is willing to look at the code, I would very much appreciate it. Thanks.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int load (char filename[], int items[], string names[], int& n);
int add(char filename[], int items[], string names[], int& n);
void sort(int items[], string names[], int n);
const int SIZE = 500;
int main(int argc, char *argv[])
{
char filename[20], answer = 'n';
int items[SIZE];
string names[SIZE];
int selection, n = 0;
cout << "Enter a filename to load: ";
cin >> filename;
do {
cout << "----INVENTORY MENU----" << endl << endl;
cout << "1. Load Inventory"<< endl;
cout << "2. Add to Inventory" << endl;
cout << "3. Search Inventory" << endl;
cin >> selection;
if (selection == 1) {
load(filename, items, names, n);
cout <<"There are " << n << " items in " << filename << "." << endl;
}
if (selection == 2) {
add(filename, items, names, n);
}
cout << "Would you like to make another menu selection? [Y/N] ";
cin >> answer;
}while(answer == 'y' || answer == 'Y');
system("PAUSE");
return EXIT_SUCCESS;
}
int load(char filename[], int items[], string names[], int& n) {
ifstream in_stream;
in_stream.open(filename);
string data;
n = 0;
char next_symbol, number[15];
do {
int i = 0;
do {
in_stream.get(next_symbol);
number[i] = next_symbol;
i++;
} while (next_symbol != ' ');
items[n] = atoi(number);
getline(in_stream, data);
cout << data << endl;
if ( data != "") {
names[n] = data;
}
cout << endl << items[n];
n++;
} while (! in_stream.eof());
in_stream.close();
}
int add(char filename[], int items[], string names[], int& n){
ofstream out_stream(filename, ios::app);
cout << "Enter an item number: ";
cin >> items[n];
cout << "Enter an item name: ";
cin >> names[n];
cout << endl << "Load section n is " << n << endl;
out_stream << items[n] << setw(15) << names[n] << endl;
out_stream.close();
sort(items, names, n);
}
void sort(int items[], string names[], int n){
cout << "BEFORE THE SWAP" << endl;
for (int i = 0; i <n; i++) {
cout << items[i] << setw(15) << names[i]<< endl;
}
int key,i;
for(int j=1;j<n;j++) {
key=items[j];
i=j-1;
while(items[i]>key && i>=0) {
items[i+1]=items[i];
names[i+1]=names[i];
i--;
}
items[i+1]=key;
}
cout << "AFTER THE SWAP" << endl;
for (int i = 0; i <= n; i++) {
cout << items[i] << setw(15) << names[i]<< endl;
}
return;
}