I have managed to read a string to a class member. My problem is that i want to read to four different class members (one string, three int) In the .txt file they are separated by a tab (This could change if its easier to read line for line)
Do you have any suggestions how one would do this?
Possibly like this - which reads the file and displays it contents. Not tried as you haven't provided a sample file contents. Uses a space/tab separator and title can't include a space/tab. If the title has/can have a space, then a different file format/read method is needed.
Since you can change your input file structure I would recommend using delimited file structure. The delimiter can be anything that won't appear in your "normal" data. Examples of delimiters: new line character, tab character, comma, semi-colon, tilde, etc.
Example using semi-colon:
1 2 3
multi-word title;isbn;copies;year published
Book 1;9834823;34;1929
Book;948736723;938;2145
Note the header line is not really required but is often present for documentation.
Any member function that doesn't change the member data is specified as const so that these methods will work on an object defined as const.
friend means that the specified function can access private variables etc.
The operators >> and << are overloaded for the Book class so that you can read/write one record of type Book with just one usage of >> or << (like you can use >> << with std::string etc).
Since you can change your input file structure I would recommend using delimited file structure. The delimiter can be anything that won't appear in your "normal" data. Examples of delimiters: new line character, tab character, comma, semi-colon, tilde, etc.
How would i implement that in code?
friend means that the specified function can access private variables etc.
Should i consider this as good practice since you generally (if i understand correctly) don't want to access the private members directly (maybe a friend is indirectly?)
This is what i come up with without dwelling deeper in friends. This works and it will print correctly when i am using the getters (yeah the should just return, i will fix that)
So obviously this is not the sharpest of code, what can i do to make it more efficient?
Its fine, but one idea...
you could make a class method that does the file work. that gets rid of the calls to setters since you could then read directly into the class members.