Reading from a text file into an array

I am having trouble reading a last name , first name from a text file into a string array. When I compile the code, it is skipping the comma and saving each line as two separate names. How can I get it to include the comma in the name?


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
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

// Function Prototypes
void selectionSort(string [], int);
void showArray(string [], int);
void showArraySorted(string [], int);

int main()
{
	const int SIZE = 43;
	int count = 0;
	string names[SIZE];
	cout << "Please enter the file name for the list of names: ";
	string fileName;
	getline(cin, fileName);
	
	

	ifstream inputFile;
	inputFile.open(fileName);


	if(!inputFile){
		cout << "ERROR opening file!" << endl;
		exit(1);
	}
	while(count < SIZE && inputFile >> names[count])
		count++;

	inputFile.close();

	showArray(names, SIZE);

	selectionSort(names, SIZE);
	showArraySorted(names, SIZE);


	return 0;
}
// Function Definitions

// shows sorted array 
void showArraySorted(string names[], int SIZE){
	cout << "The sorted names in the array are: " << endl;
	for(int i = 0; i < SIZE; i++){
		cout << names[i] << " ";
	    cout << endl;
		}
}

// sorts the contents of the array in ascnding order
void selectionSort(string names[], int SIZE){
	int startScan, minIndex;
	string minValue;

	for(startScan = 0; startScan < (SIZE - 1); startScan++){
		minIndex = startScan;
		minValue = names[startScan];
		for( int index = startScan + 1; index < SIZE; index++){
			if(names[index] < minValue){
				minValue = names[index];
				minIndex = index;
			}
		}
		names[minIndex] = names[startScan];
		names[startScan] = minValue;
	}
}


// Displays the contents of the array
void showArray(string names[], int SIZE){
	cout << "The list of names from the file: " << endl;

	for(int i = 0; i < SIZE; i++){
		cout << names[i] << " ";
    	cout << endl;
	}
	cout << endl;
}
Last edited on
In line 30, you are putting the next word from the file input stream in your array. This word ends at the first white space (directly after the comma). I think you get the full names in your array if you try to read the file line by line using getline.

1
2
3
4
5
while(count < SIZE)
{
        getline (inputFile,names[count]);
        count++;
}


There is a good example here : http://www.cplusplus.com/doc/tutorial/files/

Also, since you are using "using namespace std;" you should reconsider the name of your counter variable, because now it can/will be confused with std::count (http://www.cplusplus.com/reference/algorithm/count).

Kind regards, Nico
Thank you for your help! That seemed to do the trick. I knew it had to be something simple that I was overlooking.
Topic archived. No new replies allowed.