Hi. I would like to know if there is a way to directly store contents from a text file to an object array. This is my code:
This is the text file:
ID lname fname age phone
s111 Chand Kay 22 12345
s222 Dev Ron 19 12346
s333 Tom John 20 12456
s444 Timothy Jacob 22 12486
So as you can see, when I'm populating the arrays, I have declared separate varibles e.g string id; then I store the ids from the file into that variable, then I pass it as a parameter to the setter function to populate the array. So my question is: Is there any direct way for this? I feel like I'm wasting space by creating those variables. Or is it right?
So as you can see, when I'm populating the arrays, I have declared separate varibles e.g string id; then I store the ids from the file into that variable, then I pass it as a parameter to the setter function to populate the array. So my question is: Is there any direct way for this? I feel like I'm wasting space by creating those variables. Or is it right?
There are different ways of considering this. At the moment your setter functions don't do anything interesting, for example validating that the name does not contain digits, or validating that the phone contains digits only, or whatever checks you might need. But those functions might do some things like that, in which case directly inputting to the object's own variables might bypass those checks which could break the encapsulation of the data inside the class.
But, out of interest, you might indeed read directly from the file to the object, by overriding the input operator >> for the input stream.
edit: Notice at line 31 the declaration friendstd::istream & operator >>(
The input stream operator is made a friend of the Student class, giving it direct access to the member variables. In this case that wasn't necessary for the output stream operator as I used the proper getter functions.
Also note the use of const in the declarations of functions and parameters which will not modify the object.