This topic is 4281 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've seen this done before and I wonder if there is an easy way to do this. I want to read variables and structures from external files like this File: This_Is_A_Var = 12 //Look ^ A var This_is_another = "Hello" //< Look another!!! or structure loading File: building { name = "hospital" height = 14; //Not very tall //End of struct } I've seen it done in other programs sometimes with .h files. It should support comments - is their a something you can recommend to load this?

##### Share on other sites
What are you trying to accomplish?

1. Access an external variable defined in another cpp file.
2. Load an external data file, parse it and copy the contents into a variable.

##### Share on other sites
Quote:
 Original post by deathkrushWhat are you trying to accomplish?1. Access an external variable defined in another cpp file.2. Load an external data file, parse it and copy the contents into a variable.

The second one. I want it to define a map for my game, were buildings are and such.

##### Share on other sites
Quote:
Original post by brwarner
Quote:
 Original post by deathkrushWhat are you trying to accomplish?1. Access an external variable defined in another cpp file.2. Load an external data file, parse it and copy the contents into a variable.

The second one. I want it to define a map for my game, were buildings are and such.

An easy way to do this (probably the best), especially if you are just defining variables, is with XML.

<building>     <name>Hospital</name>     <height>14</height></building>

Oh, and there are plenty of libraries that will parse the XML for you, which makes it easy. TinyXML is one, and I think irrXML is good.

##### Share on other sites
Here is a simple reader (no error checking) for a file with lines of the form key = value.

#include <map>#include <string>#include <fstream>#include <iostream>using namespace std;typedef map<string, string> kv_file_t;void trim(string& s) {  string::size_type first = s.find_first_not_of(" \n");  string::size_type last = s.find_last_not_of(" \n");  s.assign(s, first, last - first + 1);}kv_file_t read(const char* filename) {  kv_file_t result;  ifstream file(filename);  string key, value;  while (getline(file, key, '=') && getline(file, value)) {    trim(key); trim(value);    result[key] = value;  }  return result;}

• 37
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631362
• Total Posts
2999569
×