Hey all,
I'm in my first semester of C++ programming and am working on a simple program to load words from an input file into a string array, sort that array, and then print out the array. I have the code written, which compiles and works perfectly save for one problem: no matter what I've tried the first index of the array prints out gibberish. I'm lost at this point, so I figured I'd try asking for some help. Here's the code I have written:
Code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
void sortArray(string[], int);
void printArray (string[], int);
int loadArray (string[], ifstream&);
const int SIZE = 50;
int main() {
ifstream inFile1;
inFile1.open("words1.txt");
ifstream inFile2;
inFile2.open("words2.txt");
string words1[50], words2[50];
int count1, count2;
count1 = loadArray(words1, inFile1);
cout << "Array 1, unsorted:" << endl;
printArray(words1, count1);
cout << endl << endl;
count2 = loadArray(words2, inFile2);
cout << "Array 2, unsorted:" << endl;
printArray(words2, count2);
cout << endl << endl;
sortArray(words1, count1);
cout << "Array 1, sorted:" << endl;
printArray(words1, count1);
cout << endl << endl;
sortArray(words2, count2);
cout << "Array 2, sorted:" << endl;
printArray(words2, count2);
cout << endl << endl;
}
// loadArray places value into array a from an input file.
// preconditions: input file has been succesfully opened.
// postconditions: array a is filled with i values. i values is returned.
int loadArray (string a[], ifstream& infile) {
int i = 0;
while (i < SIZE && infile >> a[i]) {
i++;
}
return i;
}
// printArray prints the values in a.
// preconditions: array hold size values.
// postconditions: prints array values, label starting at 1.
void printArray (string a[], int count) {
int i;
for (i = 0; i < count; i++) {
cout << left;
cout << setw(2) << i + 1 << " " << setw(10) << a[i] << endl;
}
}
// sortArray will put the array values into ascending order, using
// the selection sort algorithm.
// preconditions: array must be filled with size values.
// postcondition: array values are in ascending order.
void sortArray(string a[], int size) {
int i, j, min; // these hold index values to be sorted.
string temp; // must be of same type as array elements.
for (i = 0; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) { // find the index of smallest value.
if (a[j] < a[min])
min = j;
if (min != i) { // swap value at a[min] with "top" value, i.
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
}
}
The input files contain all single words, separated by a newline.
No matter what I've tried, the first index (no matter if it's 0, 1, 2... etc) prints out garbage characters followed directly by the first word in the file.
How or what can I do to remove the "garbage" that's being put in the array?
Thanks!