I need help on sorting strings, particularly complicated ones.I had to read in data from a text file

Textfile.txt

Xiao Wang 135798642
Lucie Chan 122344566
Rich Morlan 123456789
Amir Khan 975312468
Pierre Guertin 533665789
Marie Tye 987654321

I managed to put them into an array using this user-defined function (not part of my main):

#include <iostream> 
#include <fstream>
#include <string>
#include <cstdlib>     
using namespace std;

const int NUMBER_STUDENTS = 6;
string students[NUMBER_STUDENTS];

void choiceL( );

int main( )
{
     .......
     choiceL( );
.........
}

void choiceL( )
{
        ifstream inStream;
	string fileName;
	string line;

	cout << "Please, enter the name of the file: ";
	cin >> fileName;
	cout << "\n";

	inStream.open(fileName.c_str());
	if (inStream.is_open())
	{
		while (inStream.good())
		{
			for(int index1 = 0; index1 < 1; index1++)
			{
				
				getline (inStream,line);
				students[index1] = line;
				cout << students[index1] << endl;
			}
		}
		inStream.close();
	}
	else
	{
		cout << "Failure opening file " << fileName << "\n";
	}
	
	return;
}

Problem is that it stored all the students into students[0] instead of one student per cell.
I was expecting my array to look like:

string students[6] = {"Xiao Wang 135798642", "Lucie Chan 122344566", "Rich Morlan 123456789", "Amir Khan 975312468", "Pierre Guertin 533665789", "Marie Tye 987654321"}

How can I make my array look like the above when using the ifstream?

I also need to sort them by alphabetical order of their LAST NAME. I know how to sort strings alphabetically if it's just one word, but here the last names are in the middle of each string.

Can anyone please help?

Instead of reading the entire line into one string, try reading the individual fields into strings (and for now assuming that your input will always have exactly three space-separated fields per line). I'm also going to assume you've covered basic structures, so that you can sort more efficiently:

struct Student {
    string firstName;
    string lastName;
    string id;
};
Student students[NUMBER_STUDENTS];

...

inStream >> students[index].firstName;
inStream >> students[index].lastName;
inStream >> students[index].id;

As far as why it always puts things in students[0]: because that's what you tell it to do. You have more loops there than you need. The outer while() loop keeps going until the input is exhausted. The inner for() loop executes only once at a time, assigning index to 0, then reading a line and assigning it to students[index==0]. Since this isn't what you intended, just say out loud exactly what you -do- intend, and modify the code so it does what you said.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.