Array not running after file prompt.

I've been struggling with this for a few days now. I've finally got it working in pieces, but when my sorting array runs, all I get is empty space. My brain is fried at this point, I can't figure out if it's a simple fix, or a major flaw. This is my first time asking for help online, thank you in advance for any assistance.

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;


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

int main() {

	const int SIZE = 45;
	string namesList[SIZE];
	string fileName;
	fstream fileList;
	char ch;
	
	
	cout << "Enter a file" << endl;
	cin >> fileName;

	fileList.open("C:/Users/Me/Desktop/8-1Homework/nameslist.txt", ios::in);
	
			cout << "\n\nHere are the listed names, sorted chronologically:\n " <<endl;
			cout << "===================================================\n" <<endl;

	if (fileList) {
		fileList.get(ch);

		while (fileList)

		{
			
			cout << ch;

			fileList.get(ch);
		}
	}
	else {
		cout << fileName << "could not be found" << endl;
	}



	    cout << "\n\nHere are the listed names, sorted alphabetically: \n " <<endl;
		cout << "===================================================\n" <<endl;


		
		for(int i = 0; i < SIZE; ++i) {

			getline(fileList,namesList[i]);
		}


		selectionSort(namesList,SIZE);


		displayArray(namesList,SIZE);
	
		fileList.close();

		return 0;
}


void selectionSort(string array[],int size) {

	int startScan,minIndex;
	string minValue;

	for(int startScan = 0; startScan < (size - 1); ++startScan) {

		minIndex = startScan;
		minValue = array[startScan];
		for(int index = startScan + 1; index < size; ++index) {

			if(array[index] < minValue) {

				minValue = array[index];
				minIndex = index;
			}
		}
		array[minIndex] = array[startScan];
		array[startScan] = minValue;
	}
}



void displayArray(string name[],int size) {

	for(int i = 0; i < size; ++i) {

		cout << name[i] << endl;
	}
}

You already go through the file once before the for-loop. Thus, when you enter the for-loop, the file pointer is already at the end of the file and there is nothing to read. This is why the array remains empty. You need to move back to the beginning of the file so you can fill up the array. You can do that using the following two lines of code:

1
2
inputFile.clear();  // resets from EOF state to good state
inputFile.seekg(0, ios::beg); // moves file pointer back to the beginning 
Last edited on
Topic archived. No new replies allowed.