How to store lines from a file as a variable

When you use inputfile >> _organisationrecord.name it stops at the first whitespace character. Hence, only Stephen will be read and stored in organisationrecord.name.

You need to change your strategy a bit.

  1. Read the contents of the file line by line. Stop when there are no more lines left.
  2. Process each line as you seem fit.

Here’s one way to deal with the input.

std::string line;
while ( std::getline(inputfile, line) )
{   
   // Extract the employeenumber from the line
   std::istringstream str(line);
   if ( !(str >> employeenumber) )
   {
      // Problem reading the employeenumber.
      // Stop reading.
      break;
   }

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }

   _organisationrecord.name = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.occupation = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.department = line;

   std::cout << _organisationrecord.employeenumber << std::endl;
   std::cout << _organisationrecord.name << std::endl;
   std::cout << _organisationrecord.occupation << std::endl;
   std::cout << _organisationrecord.department << endl;

   OrganisationRecords.push_back(_organisationrecord);
}

Leave a Comment