How to read a file in an array and then sort the data?

So far, I have found several ways to read a text file in an array and have been able to successfully display it on the screen. I have a problem with how I sort an array from there. Sorting a text file was simple enough, but when I tried to combine both, I could not get it to work. Here is what I got so far:

int main()
{
   string players[30];
   ifstream inData("chessplayers.txt");
   if (inData.is_open())
   {
     for (int i = 0; i < 30; i++)
     {
       sort( players, players+i);       
       if (getline(inData, players[i]))
       {        
         cout << players[i] << endl;
       }
       else
       {
         break;
       }
    }
    inData.close();
  }
  else
  {
    cerr << "Failed to open file.\n";
  }
  system("pause");    
  return 0;
}

Can anyone help point me in the right direction? My job is to read the text in an array and then sort this array.

+3
source share
2 answers

It is a good idea to separate the various actions into functions. This makes your code cleaner, easier to read, and more modular.

, : , . , . , , .

( ++ 11), , , , , .

, : , , , .

#include <algorithm>
#include <deque>
#include <fstream>
#include <iostream>
#include <string>

typedef std::deque<std::string> PlayerContainer;

PlayerContainer getPlayersFromFile(std::string filename)
{
  PlayerContainer players;

  std::ifstream ifs(filename.c_str());

  std::string player;
  while (getline(ifs, player))
    players.push_back(player);

  return players;
}

void printPlayers(PlayerContainer const& players)
{
  // (this is the only part that depends on C++11)
  // for each player in players
  for (auto const& player : players)
    std::cout << player << '\n';
}

int main()
{

  std::string filename("chessplayers.txt");

  PlayerContainer players = getPlayersFromFile(filename);

  sort(players.begin(), players.end());

  printPlayers(players);
}
+1

, . :

(, + 30);

, std::string, <, > , =, etc ..

0

All Articles