Hi there! I have to read data from a file and load it into an array:

here is the data of the text file:
Team Creative
6
100 Anwar Khan
201 Belal Ahmed
150 Sara Amjad
400 Nida Khawar
342 Rehan Sheikh
341 Nadia Kanwal

My code is:

class Player
{
private:
    char* name;
    int id;
public:
 Player();
 };

class Team
{
private:
    Player* players;
    int No_Of_Players;
    char* Name;
};
Team::Team(std::string FileName)
{
    ifstream inFile;
    string sTeam_Name;
    inFile.open("input.txt");
    if(!inFile)
    {
        cout << " error in opening file " << endl;
    }

    else
    {
       string sLine;
       inFile >> Name;       // reads the name of the team
       inFile >> No_Of_Players;          // reads the number of members

       Team* t = new Team[No_Of_Players];
       for (int i=0; i<No_Of_Players; i++)
       {
           getline(inFile,sLine,' ');
           int id = atoi(sLine.c_str());
           t[i].players->Set_Id(id);


       }
    }
}

I want to ask couple of things. I have done the work for the id's but the job for names is still left. What will be the 'syntax' for that?

Why not getline by line?
So a line returns, "111 Guru Singh" ;) \r\n
Then delimit with ' ', however you want.
Store the results in an array.

std::string lineData[8]
std::vector<std::string> lineData;

Access them in any sane order.
For example,

lineData[0]              //   -> This is the number.
lineData[1, 2, 3, ...]   //   -> are parts of a name.
lineData[...] == ""      //   -> the array is finished.

Edited 3 Years Ago by Unimportant

// This is a regular array of 8 std::string objects
std::string lineData[8]; // You could use a different object string, too

// If you don't want to use the STL classes, then you'll need to make
// an array of char *
char ** lineData( new char *[8] );
lineData[0] = new char[MAX_LEN];
delete [] *(lineData + 0); // *(lineData + 1) ... *(lineData + (SZ-1))
delete [] lineData;

// Since this is such a tiny amount of data on average,
// in this case, only 2 - 8 columns, you could use the stack.
char lineData[8][MAX_LEN]; // and that's totally fine.

Edited 3 Years Ago by Unimportant

This article has been dead for over six months. Start a new discussion instead.