Let's start by maintaining your code. The first thing I would do is create an overload of operator >>
that takes an input stream and a team
object.
std::istream& operator >>(std::istream& is, team& t);
This function should delegate the operation of extracting the input to a method called do_input()
:
std::istream& operator >>(std::istream& is, team& t)
{
if (is.good())
t.do_input(is);
return is;
}
do_input
should read objects of type char
into the respective string objects in your team
class. Speaking of your team
class, it's much better to use std::string
for representation of string values:
struct team
{
...
std::string date;
std::string name;
int W, L, T;
};
This way the string can be as large enough as we need it. We no longer have to worry about a potential buffer overflow (i.e reading a string larger than 10 bytes). We can also use the convenient methods that std::string
provides.
It's further recommended that you use good variable names so that maintainers of your code can know at a glance what it means. For instance, try these:
int wins, losses, ties;
Now it is clear to me (and to others) what these names imply.
So team::do_input
is a member function that reads in the strings and integers from the file to the data members of the instance from which it is being called. Here's a full implementation:
struct team
{
public:
team& do_input(std::istream&);
private:
std::string date, name;
int wins, losses, ties;
};
team& team::do_input(std::istream& is)
{
std::getline((is >> date).ignore(), name);
is >> wins >> losses >> ties;
return *this;
}
Error reporting has been left out to keep the example concise. I hope this helped.