Putting formatted data into / reading it back out of a stream [C++]

Started by
1 comment, last by c_olin 14 years, 3 months ago
In my game I'm going to have levels stored (at least initially) in ASCII files, and read them in using an input stream in order to easily extract the tokens as floats, ints, etc. For instance, I open an input stream and pass it to the level loader. Is it possible to manually append stuff to this stream, or even put stuff into the stream without opening a file (perhaps for testing purposes) ? The level loader would then read from whatever is in the stream, regardless of where it came from. Basically what I'm I think what I'm trying to do is similar to piping. One way I thought of was to use a string stream in the file loader. The source of this string stream could then be easily interchanged between strings hard-coded into my source, or by reading a file (using a file input stream) into one large string. Are there any immediate problems with this approach? Thanks to anyone who can help!
the rug - funpowered.com
Advertisement
Your loader should load from a reference to a std::istream. Whatever invokes your loader could pass it a ifstream or a stringstream, as appropriate. Just as if the standard library was designed that way.

Stephen M. Webb
Professional Free Software Developer

You could overload the >> operator. This would provide input from any stream (standard input, file stream, etc...):

Here is a simple example (not compiled or tested):
class person {public:    friend std::istream& operator>>(std::istream& in, person& p);private:    std::string name;    int age;};std::istream& operator>>(std::istream& in, person& p) {    in >> p.name;    in >> p.age;}// User types in "Frank 21" in standard input.std::cin >> p;// File contains "Frank 21".std::ifstream file("person.txt");file >> p;

This topic is closed to new replies.

Advertisement