Would this work?

Basically I am taking in a line of code and we are supposed to use fail state to figure out which kind of format the line will follow. It will either follow one of two formats. So I am trying to say if while reading in it hits something that doesn't work it must be the OTHER kind of line. Am I using clear and fail functions correctly? It is important that when it fails the next value being read in goes into the place where it failed reading in.

So if it tries to read something in and it fails the next value read in should go into THAT value and not the next one.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void Triangle::read(istream& ins) {
 /**
     * Requires: ins is in good state.
     * Modifies: ins, vertexOne, vertexTwo, vertexThree,
     *           vertexOneColor, vertexTwoColor, vertexThreeColor.
     * Effects:  Reads triangle in forms
     *           v1 v2 v3 color
     *           v1 v1Color v2 v2Color v3 v3Color
     */

	ins >> vertexOne;
	ins >> vertexTwo;

	if (ins.fail()) {
		ins.clear();
		ins >> vertexOneColor >> vertexTwo >> vertexTwoColor >> vertexThree >> vertexThreeColor;
	}

	else { 
		ins >> vertexThree >> vertexOneColor;
	vertexTwoColor = vertexOneColor;
	vertexThreeColor = vertexOneColor;

}

An input stream enters fail state if (a) input data is invalid, (b) stream attempts to read beyond EOF or (b) tries to open non-existent file. That's what your ins.fail() would capture.
Also you can't start reading into vertexOne (line 11) or vertexTwo (line 12) before you open the stream
Finally, you set up your file reading in streams based on the layout of your files, so what you can do is to have if-else statements that select the right stream setup based on the filename
Topic archived. No new replies allowed.