Reading in File and setting variables

I'm trying to write a function read_fish that reads in a file and sets a few private class variables according to the values found in the file. Here is a more detailed description of what read_fish should do:

bool read_fish(istream &input); reads a single fish specification from input
in the format above --- the first line it encounters should begin with the word fish. It then sets the fish’s state according to the values and picture map read in and returns true. If the function cannot read a fish specification (for example, no more data, invalid data, incomplete data) the function returns false.

An example of the file it should read is (titled tank1.dat):

1
2
3
4
5
6
7
8
9
10
11
12
13
tank 35 200 
fish 1 3 10 12 0 0.5 50 minnow
><>
fish 3 5 8 20 0 0.2 100 clown
 __  
/0_\/
\__/\
fish 6 13 10 15 -1.2 0.15 200 fred
|\     ,
\`._.-'X`--.
)XoXoX=[#]#]
)XXoXXXXXX-3
/.' `-.
'

And the class definition in the header file is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Fish
{
public:
	bool read_fish(istream &input);
private:
	float start_x;
	float start_y;
	float vert_speed;
	float hori_speed;
	int height;
	int width;
	int lifetime;
	string name;
};

I pretty much have no idea how to read in the file, check if the first word in a line is "fish", and assign the 7 variables to what's found in tank1.dat for a single fish object. I'm also unsure of how to store the picture of the fish in a char array.
This is my first post, do let me know if more information is needed.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string s;
input >> s;
if (s == "fish"){
   //process the fish
   std::string line;
   std::getline(input, line);
   std::stringstream the_line(line);
   the_line >> height >> width >> /* */ >> name;
   if (not the_line) //error reading data (missing or bad type)
      return false;
   if (not the_line.str().empty()) //there is more data in the line
      return false;
   //read the picture
}
else{
   //not a fish, ¿what to do?
}


> I'm also unsure of how to store the picture of the fish in a char array.
you may use a single string, storing line breaks.
Registered users can post here. Sign in or register to post.