0

Using the solution to this thread, I have a general idea on how to read line-by-line in a text file. My issue arises on how to populate that data into my phonebook, a pointer to an array of objects.

This is what my text file outputs.

Albert, Fred
4541231234
8888 Avenue Drive

Doe, John
6191231234
1234 State Street

Smith, Mike
8791231234
0987 Drive Avenue

What I want to do, is to parse through each line and use whatever information it takes to populate my Phone Book, which is defined as.

class AddressBook
{
private:
    Contact* phoneBook[maxSize]; //array of contact pointers
    ...etc
}

class Contact
{
public:
    Contact();

    std::string firstName;
    std::string lastName;
    std::string name; //lName + fName
    std::string phoneNumber;
    std::string address;
};

I can get it to read line by line, at least I think, but I don't know where to start on how I can get it to recognize if it's a first name, last name, phone number, or address since they're all strings.

void AddressBook::writeToFile(Contact * phoneBook[])
{
    std::string line;
    std::ifstream myFile("fileName.txt");
    if (myFile.is_open())
    {
        while (getline(myFile, line))
        {
            //do something
        }
        myFile.close();
    }
}

1 Answers1

0

You have to read the contents of the file in groups of four lines.

std::string line1; // Expected to be empty
std::string line2; // Expected to contain the name
std::string line3; // Expected to contain the phone number
std::string line4; // Expected to contain the address.

And, instead of the while(getline(...)) statement, use:

while (true)
{
   if ( !getline(myFile, line1) )
   {
      break;
   }

   if ( !getline(myFile, line2) )
   {
      break;
   }

   if ( !getline(myFile, line3) )
   {
      break;
   }

   if ( !getline(myFile, line4) )
   {
      break;
   }

   // Now process the contents of lines
}

You can simplify that a little bit by using an array for the groups of lines

std::string lines[4];
while ( true )
{
   // Read the group of lines
   for (int i = 0; i < 4; ++i )
   {
      if ( !getline(myFile, lines[i]) )
      {
         break;
      }
   }

   // Process the lines
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • @R Sahu where is the `true` coming from? –  Mar 26 '19 at 04:25
  • 1
    @TylerLe. Loop until one of the `getline` calls does not succeed. At that time, you break out of the loop. – R Sahu Mar 26 '19 at 04:26
  • @R Sahu Another thing that I forgot to mention, with the name, I need to also separate them into last and first name. As you can see in the text file, it goes `lastName, firstName`, So I need to store Albert as a last name variable and Fred as a first name variable. How can I separate the two and not include the commas? Other than that issue, I got it to work thanks to your contribution! –  Mar 26 '19 at 04:54