Lets say I have a text file with a bunch of names on it.
The position where each element start remains constant throughout the lines(example, last name starts after 25 spaces).
I want to save each name into a respective string. like this
Carlos Miguel Rodriguez Soto 01262015015300015560078739922347872342345
Felix Gabriel Perez Roman 01192015009020509401478723456437873451234
David Piere Soto Colon 12232014111340912410578735623453054562345
You don't need to substring the line into first, last etc names in this case but by defining a Person struct you can read off the data directly into the data-members of the object and save them in a std::vector<Person>. This, of course, assumes that the file is uniform in that each person has all the attributes, no missing data or other irregularities.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
struct Person
{
std::string m_firstName;
std::string m_middleName;
std::string m_lastName;
std::string m_maidenName;
Person(){}
Person(const std::string& fName, const std::string& midName, const std::string& lName, const std::string& mName)
: m_firstName(fName), m_middleName(midName), m_lastName(lName), m_maidenName(mName){}
};
std::ostream& operator << (std::ostream& os, const Person& p)
{
os << p.m_firstName << " " << p.m_middleName << " " << p.m_lastName << " " << p.m_maidenName << '\n';
return os;
}
int main()
{
std::ifstream inFile("F:\\test.txt");
std::vector<Person> persons{};
if(inFile)
{
Person p{};
while (inFile >> p.m_firstName >> p.m_middleName >> p.m_lastName >> p.m_maidenName)
{
if(inFile)
{
persons.push_back(p);
}
}
}
for (constauto& elem : persons)
{
std::cout << elem ;
}
/*TEXT FILE
Carlos Miguel Rodriguez Soto
Felix Gabriel Perez Roman
David Piere Soto Colon
PROGRAM OUTPUT
Carlos Miguel Rodriguez Soto
Felix Gabriel Perez Roman
David Piere Soto Colon*/
ps: also ignoring the numbers at the end of each row as mentioned but if they are present in a file and not required they can be read into a dummy variable and discarded