Skip to main content
GameDev.net gamedev.net
🔒 Locked

Loading class information from a file

Started by ChrisRX Sep 3, 2008 at 8:58 AM 4 replies 850+ views
Original Post
ChrisRX
ChrisRX
I pretty much understand how to code a tile engine in sdl from the LazyFoo article, but I want to know how to code something a bit more .......dynamic? A tile engine would be a bit excessive for a platformer I think (which is what I'm trying to create) So I'm creating every part of the game as separate objects but at the moment I'm hardcoding them into the cpp files and it's getting a bit excessive. Could someone please explain how to load object info from a file using C++. A simple example will probably suffice, such as 2 objects with 2 variables (x and y)
Enalis
Enalis
If you're talking about simple fileio, you're better off reading some tutorials and doing some examples...

For a quick intro, if you are familiar with cin, cout... they are part of the std namespace in c++ which is the basic functionality we all love.

cin and cout are called streams, which are meant to "stream" data from source to destination. They just happen to be special types of streams for reading in from the standard input (keyboard most of the time), and outputting to the standard output (monitor).

File io works the same way in c++:
simple file io article

In your case for reading, you'll create a file input stream:
#include <fstream.h>   // file I/O#include <string>using std::ifstream;   // ifstream is short for "in file stream"using std::string;// in this case we must define our streamifstream fin;          // I like calling it something similar to the std, like cin.fin.open("myfile.txt", ios::in);// then simply use it like cin...string line_from_file;fin >> line_from_file;// w00t.


I hope this helps, I typed it quickly at work, so I also hope it's without error... have fun!
Douglas Eugene Reisinger II
Projects/Profile Site
Zakwayda
Zakwayda
One minor point: You can (and should) write this...

ifstream fin("myfile.txt");

Rather than this...

ifstream fin;fin.open("myfile.txt", ios::in);

File streams (and streams in general) in C++ are RAII objects, and (generally speaking) are intended to be used as such. (Also, I'm pretty sure that you do not need to include the ios::in argument when creating an object of type ifstream.)
dmatter
dmatter
Quote:
Original post by jyk
(Also, I'm pretty sure that you do not need to include the ios::in argument when creating an object of type ifstream.)
Nope, it's not needed.

Further,

// then simply use it like cin...string line_from_file;fin >> line_from_file;

Is only going to read a line from a file if there happen to be no spaces. Line reading is done like this:

std::string line_from_file;std::getline(fin, line_from_file);


joe_bubamara
joe_bubamara
I think you should take a look at open-rj: http://openrj.sourceforge.net/ .

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.