From 40bf33c9df2d24219826147417ad07dd21e35d17 Mon Sep 17 00:00:00 2001 From: Feffernoose Date: Mon, 7 Oct 2013 23:32:37 -0400 Subject: 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. --- freevars.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 freevars.cpp (limited to 'freevars.cpp') diff --git a/freevars.cpp b/freevars.cpp new file mode 100644 index 0000000..ca69f6c --- /dev/null +++ b/freevars.cpp @@ -0,0 +1,45 @@ +#include "freevars.h" +#include + +freevars::freevars() +{ + vars = new map* >(); +} + +void freevars::addVar(string name, string filename) +{ + vector* eltlist = new vector(); + + ifstream infile(filename.c_str()); + if (infile) + { + string line; + + while (getline(infile, line)) + { + eltlist->push_back(line); + } + } else { + eltlist->push_back(""); + } + + (*vars)[name] = eltlist; +} + +string freevars::parse(string in) +{ + string res(in); + + for (map* >::iterator it = vars->begin(); it != vars->end(); it++) + { + string tofind = "$" + it->first + "$"; + size_t fpos = res.find(tofind); + if (fpos != string::npos) + { + int r = rand() % it->second->size(); + res.replace(fpos, tofind.length(), (*it->second)[r], 0, string::npos); + } + } + + return res; +} \ No newline at end of file -- cgit 1.4.1