Reading string from file then selection sorting

Ok so this is a time around I need to read strings from a file and sort them using Selection sort. I took a bit of another program that read strings using a getline function into an array but, I can't get the rest of the code to work. Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

void selectionSort(string [], int);
void showArray(string [], int);

int main()
{
	const int SIZE = 29;
		string array[SIZE]; 
		int i=0; 
		string name; 

		ifstream in ("names.txt"); 

		if (in.is_open()) 
			{
				while (! in.eof() ) 
				{
					getline (in,name);
					array[i] = name;
					cout << array[i] << endl;
					i++;
				}
				cout<<"\n";

				in.close(); 
			}

	cout << "\tThe unsorted string is: \n";
	showArray(name, SIZE);
	selectionSort(name, SIZE);
	cout << "\n\tThe sorted string is: \n";
	showArray(name, SIZE);
	system("pause");
	return 0;
}


void selectionSort(string name[], int elems)
{
	int startScan, minIndex;
	string strName;
	for(startScan = 0; startScan < (elems - 1); startScan++)
	{
		minIndex = startScan;
		strName = name[startScan];
		for(int index = startScan + 1; index < elems; index++)
		{
			if(name[index] < strName)
			{
				strName = name[index];
				minIndex = index;
			}
		}
		name[minIndex] = name[startScan];
		name[startScan] = strName;
	}
}


void showArray(string name[], int elems)
{
	for(int count = 0; count < elems; count++)
		cout << count << ": " << name[count] << endl;
}
closed account (SECMoG1T)
you confused some variables here
1
2
3
string array[SIZE]; /// this is an array of strings
int i=0; 
string name;  ///this is a string variable not an array 


1
2
3
4
5
6
7
       cout << "\tThe unsorted string is: \n";
	showArray(name, SIZE);             /// name is not an array, it is a string 
	selectionSort(name, SIZE);         /// replace all instances of name with 
	cout << "\n\tThe sorted string is: \n"; /// your variable array. because your functions
	showArray(name, SIZE);             /// are taking an array parameter.
	system("pause");
	return 0;


hope it works XD.
Last edited on
Topic archived. No new replies allowed.