For my assignment this week, I was supposed to create a program that would read in names from a file, sort them, then output the names sorted. I attempted to do it as a insertion sort, and seemed to have failed miserably... if anybody could point me in the right direction that would be great :D All of my errors appear in the functions I've 'created', starting from strcpy()
Also please point out any poor coding habits. Though I am a noob at this, I realize it doesn't excuse my inability to do things right.
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
void sortString(char array[], int num);
void outputString(char array[], int num);
int main() {
int columns=30, rows=0;
char filename[30], letter;
ifstream fin;
cout << "Enter the file name: ";
cin >> filename;
fin.open(filename);
if (!fin) {
cout << "Failure to open the file.";
} else {
while (fin >> letter) {
if (letter == '\n')
rows++;
}
fin.clear();
fin.seekg(0,ios::beg);
char name[rows][columns];
rows = 0;
while (fin.get(name[rows][columns])) {
rows++;
}
sortString(name, rows+1);
outputString(name, rows+1);
}
return 0;
}
void sortString(char array[], int num) {
int i, j;
char check[num][30];
for (i=1; i<num; i++) {
strcpy(check, array[i][30]);
for (j=1; j>=1 && (strcmp(check, array[30][j-1])==1); j--) {
array[j][30] = array[j-1][30];
array[j-1][30] = check;
}
}
}
void outputString(char array[], int num) {
for (int i=0; i<num; i++) {
cout << array[i][30] << endl;
}
}