Hey, so in my c++ class we just started working with classes and I/O streams using .txt files. Basically, we have classes for Point and Color that define how a coordinate point or an RGB color is read from a .txt file, and both are correct. I am currently working on a function that reads in a Triangle object using 2 different formats:
vertex1 vertex2 vertex3 color
OR
vertex1 vertex1color vertex2 vertex2color vertex3 vertex3color
This is what the format would look like in a .txt file:
(10,10) (50,20) (20,40) 200 0 5
(80,5) 0 200 5 (50,20) 200 0 5 (85,90) 50 0 5
This is the code I came up with but it's incorrect.
NOTE: THE INPUT IS ASSUMED TO BE CORRECT. I don't need to check for bad input. I just need to properly read in one of the two formats.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void Triangle::read(istream& ins) {
ins >> vertexOne >> vertexTwo;
//If the value read is a color, then the stream fails and thus it must be
//the other format
if (ins.fail()) {
ins.clear();
ins >> vertexOne >> vertexOneColor >> vertexTwo >> vertexTwoColor >>
vertexThree >> vertexThreeColor;
}
else {
//finishes reading the stream and sets all vertex colors to one color
ins >> vertexThree >> vertexOneColor;
vertexTwoColor = vertexOneColor;
vertexThreeColor = vertexOneColor;
}
| |
This is the read function. I am not allowed to change this:
1 2 3 4 5
|
istream& operator >> (istream& ins, Triangle& tri)
{
tri.read(ins);
return ins;
}
| |
I've tried several variations of this same general idea, but none have been correct. I think I might need to use getline or a junk string variable to handle the leftover values after clear(), but at this point I'm really not sure what the best approach would be. I've been at this for several days and I can't wrap my head around it. My instructors have been less than helpful so I'd really appreciate some direction. If you need anymore information, let me know.
Thanks guys