So I just was wondering how i can read from a file, get the line, assign it to a variable, then go to the next line get it and assign it to another variable. Here some example maybe it could help.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // sort function
#include <fstream>
#include <sstream>
#include "Student.h"
#include "print.h"
usingnamespace std;
int main()
{
string line;
string id;
string name;
string address;
string phone;
vector<Student> list;
ifstream in;
in.open(argv[1]);
while (getline(in, line))
{
//get id
//get name
//etc.
}
Student newStudent(id, name, address, phone); //pushback into vector of object
1 2 3 4 5 6 7 8
529173860
Dick B. Smith
879 Maple Road, Centralia, Colorado 24222
(312) 000-1000
925173870
Harry C. Anderson
635 Main Drive, Midville, California 48444
(660) 050-2200
this is the file i want to read. Hopefully it helps! Thanks.
while (!in.eof())
{
getline(in, id, '\n');
getline(in, name, '\n');
getline(in, address, '\n');
getline(in, phone, '\n');
Student newStudent(id, name, address, phone);
//Once the four variables are stored, it'll continue on with
// the file, and will continue making students until it reaches the end of the file.
}
If you actually want the same behavior as the original loop, put all the getline() calls into the condition like your original post, combined with &&. Checking eof() will only work after you have tried and failed to read the file, resulting in an incorrect student object at the final loop.