## Recommended Posts

NiPER    122
I'm working on a text-based RPG game and I want all data to be stored in .txt files, so I can edit and test easily. I want it to look something like this in the .txt file: //Monster ID,lvl,hp,....... 1,54,324,...... I suppose reading these values in an array would be the best, but how do I do? I've read a few tutorials about IO and solved this by first reading the first values with fin.get(char, 100, ','), where fin is the object I created with ifstream. Then fin.eof(); Then ignore until I come to another , and use fin.get again. This felt like a very bad solution so I guess there must be a better way. I'd really appreciate any help, thanks. In case you didn't understood my explanation of what I did, just skip it and please tell me a solution to read in these values in an array instead. =) -Niklas

##### Share on other sites
moagstar    263
Here is a cheap and easy way of doing it, I suggest you tinker with it a bit though to get your desired effect

In the text file :

31 54 324

And then in C++

std::ifstream in("source.txt");int inInt;in &gt;&gt; inInt;int* attribs = new int[inInt];for(int i=0;i&lt;inInt;i++)   in &gt;&gt; attribs[i];

##### Share on other sites
MaulingMonkey    1728
Personally, I'd go with the overkill approach and use the Boost Spirit Library.

Simple example:

#include <boost/spirit.hpp>using namespace boost::spirit;#include <fstream>#include <string>#include <vector>using namespace std;struct monster{    string name;    unsigned int id;    unsigned int level;    unsigned int hp;};void load_some_rpg_data( void ){    ifstream file( "data.txt" );    vector< monster > monsters;    while ( file )    {        string line;        getline( file , line );        if ( line.empty() ) continue ; //ignore blank lines        monster m;        parse( line.begin() , line.end()            ,   (+( anychar_p - ',' )) //read 1 or more (+) characters that arn't commas...                [ assign_a( m.name ) ] //...and assign the whole shebang to m.name            >>  "," >> uint_p[ assign_a( m.id ) ] //read a comma, then an unsigned integer, and assign it to m.id            >>  "," >> uint_p[ assign_a( m.level ) ] //read a comma, then an unsigned integer, and assign it to m.level            >>  "," >> uint_p[ assign_a( m.hp ) ] //read a comma, then an unsigned integer, and assign it to m.hp            );        monsters.push_back( m );    }}

The Boost Spirit library is EXTREMELY flexible, and not too hard to use for simple cases either :-). This example would parse a file like:

Ogart the Ugly,1,1,10Your mom,2,10000,10000Knight of the Pie,3,14159,26535

Etc...