Gathering information

I am working on a program which allows the user to enter information about a student, the inputs are: surname, last name, courses.
So an example of how it would look when they type it in would be as following:

Robert Johnson math1,math2
Albert wilsson english5,french3

Ending the input by pressing Ctrl+D. After the input the program will write this out in the terminal as following:

[Surname]: Robert, [Last name]: Johnson, [Courses]: math1,math2
etc...

The program is taking care of the input and output through two operators (which can be seen in the code below). My issue is that I have not found a way to write a while loop which can take in as many people as possible. What I have now is a for loop which let me write three people, but I would like it to be possible to put in any amount of people.

Thanks in beforehand!

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <iomanip>
#include <sstream>
#include <tuple>
#include <vector>
#include <algorithm>

using namespace std;

class Student
{
public:
  Student()
    : surname{}, lastname{}, courses{} {}

  Student(string const & n, string const & l, string const & c)
    : surname{n}, lastname{l}, courses{c} {}


  friend istream & operator >>(istream & is, Student & s)
  {
    string surname;
    string lastname;
    string courses;

    getline(is, surname, ',');
    getline(is, lastname, ',');
    getline(is, courses, ';');
    
    istringstream nis{surname};
    nis  >> s.surname;
    istringstream iis{lastname};
    iis  >>  s.lastname;
    istringstream cis{courses};
    cis  >>  s.courses;

    return is;
  }

  friend ostream & operator <<(ostream & os, Student & s)
  {
    return os << "({Surname}: " << s.surname << ", {Last name}: " << s.lastname << ", {Courses}: " << s.courses << ")";
  }

private:
  string surname;
  string lastname;
  string courses;
};


int main() 
{
  vector <Student> st(3);
  int n{1};

  for (Student & i: st)
  {
    cin >> i;
  }

  for (Student & i : st)
  {
    cout << i << endl;
  }

  return 0;
}
Last edited on
Normally you would have a loop like this:
1
2
3
4
5
6
vector<Student> students;
Student student;
while(cin >> student)
{
  students.push_back(student);
}
Works with that piece of code, cheers!

However it only types out the first person, regardless of how many I type in. Been trying with some vectors but can't seem to get it to work. Any tips on how that could be solved?

Thanks in beforehand.

[Edit]
Found the solution, had the ';' left from the last getline in the operator >>.
Thanks for the help!
Last edited on
Topic archived. No new replies allowed.