Hey guys, I've been working on a little game project recently and have come into a bit of trouble, I've scoured google for a solution but can't seem to find it.
I have a few randomly made shop names stored in a text file called town.txt
The data inside is something like this
HT General 1 1
John Smith Traders 1 1
Novar General Wares 1 1
Mad's Weapon Store 1 2
Army Barracks 2 10 4
My main goal is that when reading the information, I can store each part of the line separately.
buildingtype = secondpart (firstnumber);
if(buildingtype == 1) //store
{
cout << firstpart (base name) << endl;
shoptype = secondpart //1 is general store 2 is weapon store
}
else if(buildingtype == 2)//base
{
cout << firstpart (shop name) << endl;
basepopulation = secondpart
basealignment = thirdpart
}
so that I can run through random stored data and have a whole variety of shops/buildings.
At the moment I can both randomly generate and read the file but when the file is read into a string, the data is saved as 'HT General 1 1' as opposed to 'HT General', the problem with grabbing each individual word is that there is a chance that a building name can be two-five parts long.
I thought that perhaps I could store the data in the text file as "'HT General' 1 1" with apostraphes around the content, but I'm not entirely sure how this work.
#include<iostream>
#include<sstream>
#include<string>
usingnamespace std;
class Info {
private:
string name;
int type;
int etc;
int misc;
public:
Info() : type(0), etc(0), misc(-1) {
}
void parse(const string& line);
void dump() const;
};
void Info::parse(const string& line) {
istringstream iss(line);
getline(iss, name, '\t');
iss >> type;
iss >> etc;
if(!iss.eof()) {
iss >> misc;
}
}
void Info::dump() const {
cout << "name = " << name << "\n"
<< "type = " << type << "\n"
<< "etc = " << etc << "\n";
if(-1 != misc)
cout << "misc = " << misc << "\n";
}
int main() {
constchar data[] = // pretend file
"John Smith Traders\t1\t1\n""Novar General Wares\t1\t1\n""Mad's Weapon Store\t1\t2\n""Army Barracks\t2\t10\t4\n";
istringstream iss(data); // could be ifstream instead
string line;
while(getline(iss, line)) {
Info info;
info.parse(line);
info.dump();
}
return 0;
}
Andy
PS Excel and similar can write and edit tab-delimited (and csv) files, as well as their own formats.
PPS To make you code look pretty (and provide line numbers so people can comment on particular bit of it), see article "How to use code tags" http://www.cplusplus.com/articles/jEywvCM9/