I am trying to create a loop to split lines of a text file into different vectors where "persons" contains all lines, "v1" contains names, "v2" contains ages & "v3" contains pets. I have been able to push all lines to "persons" but how would I iterate over persons so that persons[0] = name, persons[1] = age, persons[2] = pet, persons[4] = name etc....? The code I have written gets stuck in an infinite loop.
#include <io>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream people("myfile.txt");
vector<string> persons;
vector<string> first_names;
vector<float> ages;
vector<string> pets;
string l;
float age;
if(!people)
{
printf("fail");
system("pause");
return -1;
}
else
{
while(getline(people, l))
{
if (l.size() > 0)
{
people.push_back(l)
}
}
int num = people.size();
for (int i = 0; i < num; i + 3)
{
first_names.push_back(people[i]); // These are the
ages.push_back(stof(people[i+1])); // lines created to
pets.push_back(people[i+2]); // push to seperate
} // arrays.
return 0
}
}
Text file example
Bob
25.5
Snake
Kerry
29.5
Dog
This is wrong:
for (int i = 0; i < num; i + 3)
It should be
for (int i = 0; i < num; i += 3)
otherwise i
will always be 0 and never more than num-1
.