Get line and assigning to variables

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>  // sort function
#include <fstream>
#include <sstream>
#include "Student.h"
#include "print.h"
using namespace 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.
closed account (NyqLy60M)
1
2
3
4
5
6
7
8
9
10
11
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.
}
Last edited on
This is perfect, thank you so much for the help! Greatly appreciated.
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.
Topic archived. No new replies allowed.