Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Help for data reading and writing using objects

Hi All,
The follwing program I wrote to read data from a files and write them into another file. But it didnt work. Pls tell how to correct my program.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

class Node
{
friend ostream& operator<<(ostream&, const Node&);
friend istream& operator>>(istream&, Node&);

public:
Node(double, double, double);
~Node() {};

private:
double node1;
double node2;
double node3;

};

Node::Node(double node1, double node2, double node3)
{
this->node1=node1;
this->node2=node2;
this->node3=node3;
}

ostream& operator<<(ostream &out, const Node& nodes)
{
out<<nodes.node1 <<" "<<nodes.node2 <<" " <<nodes.node3 << endl;
return out;
}

istream& operator>>(istream &in, Node& nodes)
{
in>>nodes.node1 >> nodes.node2>>nodes.node3;
return in;
}

int main()
{
Node aNode;
ifstream Infile;
Infile.open(" asum.in");
Infile>>aNode;

ofstream Outfile;
Outfile.open("asum");
Outfile<<aNode;
// Node node(0,0,0);
// cin>>node;
// cout << node;
Infile.close();
Outfile.close();
}

I could work with this program to read from screen and print them on screen. But I dont know how to use this for read from files. Pls help me.

Thanks lot in advance.
[1669 byte] By [sitha] at [2007-11-11 10:05:09]
# 1 Re: Help for data reading and writing using objects
u have a small problem that u must specify the three arguments for the class constructor :

u have made the class constructor take three args to construct the object so this could not work : Node aNode; as it can't know haw to construct the "aNode" ..

the solution is either to put an empty constructor or u specify three starting values like :
Node aNode(1,2,3);

If u want to be able to change those values in any place in the programme so put an empty default construnctor or make a function to do that work .
Amahdy at 2007-11-11 20:59:25 >
# 2 Re: Help for data reading and writing using objects
Thanks a lot. Yeah I understand where I made a mistake. If I make an empty constructor, will it make any trouble in reading? because if anyline has four nodes it may read all four nodes, but I need only three nodes and I should check their validity as well.
So which way is good for my purpose?

Thanks.
sitha at 2007-11-11 21:00:31 >
# 3 Re: Help for data reading and writing using objects
Yea overloding an empty constructor is usually used for this , like int :
sometimes we write int a; only and sometimes we want it int a=5;
just care when reading , or writing as well first if the node is empty then don't write it ..
u can make this by putting default values in the empty constructor that coulden't never occure like
-1 -1 -1 ; then before writing check if the three nodes are -1 so this node is null and must not be written , else write it and it's ok .
Amahdy at 2007-11-11 21:01:36 >