Input/Output operator overloading

Hey, so I've never handled i/o operator overloading before and yet my beginner's course expects me to know how it works. I need to implement the top 2 functions you see below for a lab, and the input will always be in the following format: (x,y)
That is, the input includes the parentheses, an int x, a comma, and another int y. Then Point::write() will output in the same format.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  void Point::read(istream& ins) {
	/**

	* Requires: ins is in good state.

	* Modifies: ins, x, y.

	* Effects:  Reads point in form (x,y).

	*/


	return;

}    

void Point::write(ostream& outs) {
    
	/**
    
	* Requires: outs is in good state.
    
	* Modifies: outs.
    
	* Effects:  Writes point in form (x,y).
    
	*/

    

	return;

}

// Your code goes above this line.

// Don't change the implementations below!



istream& operator >> (istream& ins,  Point& pt)
{
    
	pt.read(ins);
    
	return ins;

}



ostream& operator << (ostream& outs, Point pt)
{
    
	pt.write(outs);
    
	return outs;

}


I thought that maybe a solution to Point::read() might look like this:
1
2
3
4
5
6
7
8
void Point::read(istream& ins) {
        char c;
        Point pt;

        ins >> c >> pt.x >> c >> pt.y >> c;
	return;

}  


But honestly I have no idea. Tried looking up tutorials but I'm just confusing myself about how to write it. Any help is appreciated.
I assume you have a class named Point which has member variables named x and y.

Your attempt at the code looks almost right, it just does something extra which isn't needed. Since read() is a member function of the class, there's no need here to declare a separate Point variable.

Something like this:
1
2
3
4
5
6
7
8
9
10
11
void Point::read(istream& ins) {
    /**
    * Requires: ins is in good state.
    * Modifies: ins, x, y.
    * Effects:  Reads point in form (x,y).
    */

    char c;
    
    ins >> c >> x >> c >> y >> c;
}


The return statement is optional, it isn't needed here.

Note in the provided code (the part which you are not supposed to modify), the functions for the operators << and >> are not member functions. They are stand-alone functions. As such, they use a Point parameter passed by reference.

In those provided functions, the return is needed, because the modified stream variable is to be returned. It enables chaining of input or output operations in statements such as
cout << "a = " << a << " b = " << b << '\n';


Awesome, thanks!
Topic archived. No new replies allowed.