Hi, I'm having a problem with displaying names from a text file. I'm passing the names from the text file to an array that will be sorted, but I'm not getting the names to show like I want them to.

It should display the different names as Last, First

But it comes up as
Last,
First

I believe that I'm not passing the names from the text file to the array properly, but I'm not sure what I should do.

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

//function prototypes
void selectionSort(string[], int);
void showArray(string[], int);

int main()
{
    //Input file stream object
    ifstream inputFile;    
    //constant for number of names
    const int NUM_NAMES = 20;       
    //array that holds names    
    string names[NUM_NAMES];     
    //open the file
    inputFile.open("namesFile.txt");
    
    // Read names from file into array
    for(int count = 0; count < NUM_NAMES; count++)
        inputFile >> names[count];
                   
    //close file
    inputFile.close();
                                
    cout<<"Unsorted names :\n\n"; 
    
    //show and then sort names                          
    showArray( names, NUM_NAMES );
    selectionSort( names, NUM_NAMES );
    
    //clear screen for readablity
    system("cls");
    
    //show sorted names
    cout<<"Sorted names :\n\n";
    
    showArray( names, NUM_NAMES );
                                   
    return 0;
}

I'm not looking for someone to do my homework for me, I just need a push in the right direction.

could you please post your code for your showArray() function. it looks like the problem will be in there.

could you please post your code for your showArray() function. it looks like the problem will be in there.

void showArray( string names[], int NUM_NAMES )
{
     for(int count= 0; count<NUM_NAMES; count++)
        cout << names[count] << endl; 

        system("pause"); 
}

alright the problem is you are using endl after each name so it wil display each name on a seperate line. if you want to displa it as Last, First then this should work well for you.

void showArray( string names[], int NUM_NAMES )
{
     for(int count= 0; count<NUM_NAMES; count+=2)
     {
          cout << names[count] << ", " << names[count +1] << endl;
     }
     cin.get();  // <-  use this instead of system("pause")
}

Thanks, that got me most of the way there. I had to change NUM_NAMES from 20 to 40 to display all the names I had.

Now that that's fixed, my selection sort is sorting screwy. I'm going to try to get on my own though.

Thanks again.

glad to help

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.