diff options
| author | Feffernoose <fefferburbia@gmail.com> | 2013-10-07 23:32:37 -0400 |
|---|---|---|
| committer | Feffernoose <fefferburbia@gmail.com> | 2013-10-07 23:32:37 -0400 |
| commit | 40bf33c9df2d24219826147417ad07dd21e35d17 (patch) | |
| tree | 91a06d9c5aa4adbe927bddec5522e1b27c6756e5 /freevars.cpp | |
| parent | d4b193e6e7fdefc66d9698337581b960c30844ea (diff) | |
| download | rawr-ebooks-40bf33c9df2d24219826147417ad07dd21e35d17.tar.gz rawr-ebooks-40bf33c9df2d24219826147417ad07dd21e35d17.tar.bz2 rawr-ebooks-40bf33c9df2d24219826147417ad07dd21e35d17.zip | |
Implemented freevars
Arbitrary variable tokens can now be defined (though at this point only in the code itself) as a pair of a variable name and a filename pointing to a plain text file containing a newline-delimited list of elements. When a token of the form $name$ (where name is the name of a variable) is encountered, the output will include a random element from the appropriate list. The variables $name$ and $noun$ are hard-coded at this point, but the program will not crash if names.txt and nouns.txt do not exist and will instead just silently ignore the variables.
Diffstat (limited to 'freevars.cpp')
| -rw-r--r-- | freevars.cpp | 45 |
1 files changed, 45 insertions, 0 deletions
| diff --git a/freevars.cpp b/freevars.cpp new file mode 100644 index 0000000..ca69f6c --- /dev/null +++ b/freevars.cpp | |||
| @@ -0,0 +1,45 @@ | |||
| 1 | #include "freevars.h" | ||
| 2 | #include <fstream> | ||
| 3 | |||
| 4 | freevars::freevars() | ||
| 5 | { | ||
| 6 | vars = new map<string, vector<string>* >(); | ||
| 7 | } | ||
| 8 | |||
| 9 | void freevars::addVar(string name, string filename) | ||
| 10 | { | ||
| 11 | vector<string>* eltlist = new vector<string>(); | ||
| 12 | |||
| 13 | ifstream infile(filename.c_str()); | ||
| 14 | if (infile) | ||
| 15 | { | ||
| 16 | string line; | ||
| 17 | |||
| 18 | while (getline(infile, line)) | ||
| 19 | { | ||
| 20 | eltlist->push_back(line); | ||
| 21 | } | ||
| 22 | } else { | ||
| 23 | eltlist->push_back(""); | ||
| 24 | } | ||
| 25 | |||
| 26 | (*vars)[name] = eltlist; | ||
| 27 | } | ||
| 28 | |||
| 29 | string freevars::parse(string in) | ||
| 30 | { | ||
| 31 | string res(in); | ||
| 32 | |||
| 33 | for (map<string, vector<string>* >::iterator it = vars->begin(); it != vars->end(); it++) | ||
| 34 | { | ||
| 35 | string tofind = "$" + it->first + "$"; | ||
| 36 | size_t fpos = res.find(tofind); | ||
| 37 | if (fpos != string::npos) | ||
| 38 | { | ||
| 39 | int r = rand() % it->second->size(); | ||
| 40 | res.replace(fpos, tofind.length(), (*it->second)[r], 0, string::npos); | ||
| 41 | } | ||
| 42 | } | ||
| 43 | |||
| 44 | return res; | ||
| 45 | } \ No newline at end of file | ||
