0

I have a text file:

bob,10,20,30
joe,50,60,50
shelly,20,15,29

that I want to read into a vector of type student, defined:

   class student
    {

      public:
        string name;
        int exam1;
        int exam2;
        int exam3;

            student (string s, int x, int y, int z)
            {
              name = s;
              exam1 = x;
              exam2 = y;
              exam3 = z;
            }
    };

Using iterators begin() and end(), I am able to store the strings, line by line, but I want to be able to parse these strings to store a students name and his/her exam scores, but I don't know it can be done.

I read about 'find' and 'substr' from the string class but I'm a bit new to iterators and vectors in general. How can I parse the vector using 'find' and 'substr' when it is of type ? I know there may already be many errors in my code or thinking.

main:

int main()
{
  //Open file and create iterator
  ifstream file ("test.txt");
  istream_iterator<string> begin (file), end;

  vector<student> vec (begin, end);
}
SSOPLIF
  • 311
  • 1
  • 4
  • 15
  • 1
    possible duplicate of [Simple string parsing with C++](http://stackoverflow.com/questions/2880903/simple-string-parsing-with-c) – Nikko Jan 24 '15 at 20:46

1 Answers1

4

In order to have the standard C++ library parse the strings for you, supply a custom input operator >> for the student class:

istream &operator >>( istream &input, student &res ) {
    string s;
    int x, y, z;
    char comma; // Ignored
    getline(input, s, ',');
    input >> comma >> x >> comma >> y >> comma >> z;
    res = student(s, x, y, z);
    return input;
}

This implementation is less efficient than it could be, because it requires copying. You could make it more efficient by writing directly into the fields of student, because they are public:

istream &operator >>( istream &input, student &res ) {
    getline(input, res.name, ',');
    char comma; // Ignored
    input >> comma >> res.exam1 >> comma >> res.exam2 >> comma >> res.exam3;
    return input;
}

Finally, you could make the fields private, and declare the operator >> a friend of the student class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • When I try your second example, I get the error 'std::istream& student::operator>>(std::istream&, student&)' must take exactly one argument – SSOPLIF Jan 24 '15 at 21:50
  • @filposs I think this is because you declared the operator inside the class without making it a `friend` of the class. Once you mark it as `friend`, it becomes non-member, and is allowed to take the second parameter. See [this Q&A](http://stackoverflow.com/q/3312269/335858) for information. – Sergey Kalinichenko Jan 24 '15 at 21:58