Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

READING FROM A FILE!

Status
Not open for further replies.

NaveenArora

Programmer
Sep 1, 1999
3
0
0
IN
Hi,<br>
If one wants to read from a file (thru istream)<br>
directly into a user defined structure<br>
without putting into a string first and then<br>
extracting values, how it is possible?<br>
Thanks<br>
Endrew<br>

 
Hi there!<br>
<br>
You need to overload the input stream operator &gt;&gt; for <br>
your class like this:<br>
<br>
<br>
istream& operator&gt;&gt;(istream& in,yourClass& theClass)<br>
{<br>
in &gt;&gt; theClass.attribute1;<br>
in &gt;&gt; theClass.attribute2;<br>
.<br>
.<br>
.<br>
in &gt;&gt; theClass.attributeN;<br>
<br>
return in;<br>
}<br>
<br>
and you use it like this:<br>
<br>
cin &gt;&gt; theClass;<br>
<br>
<br>
Some things to keep in mind:<br>
<br>
1. Don't declare this function as a method in your class.<br>
If you do, you will not be able to use the overloaded<br>
operator correctly. Try it!<br>
<br>
2. Make the function a friend of your class. That way you<br>
will be able to access the private attributes of your<br>
class without having to go through an access method.<br>
This is one of the few places where declaring something<br>
as a "friend", and thereby violating data encapsulation, actually makes sense.<br>
<br>
Hope this helps!<br>
<br>
-Mart311
 
Hello Mart311,<br>
<br>
Thanks for ur reply.<br>
Actually in my project there r many configuration files.<br>
All files have different values of differnt types some 3,4 etc but they have same way of formating and reading and commenting.<br>
what differs is the structure of the files.<br>
I wanted to make a template class which takes a struct or <br>
a class as a input. and a function returns values filled array of structures (array because there can be &gt;1 entries) directly after reading from the file.<br>
Then the format of the cfg files is known to only that class<br>
and will avoid code replication.<br>
But now i think it wont be possible.<br>
<br>
Naveen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top