school/cs142/lab10/util.cpp

61 lines
1.6 KiB
C++

#include <vector>
#include <string>
using namespace std;
#include <cstdlib>
#include "util.h"
vector<string> tokenize(const string & str, const string & delimiters) {
vector<string> tokens;
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
bool parse_n_load(const string & input, string & name, string & type,
int & max_hp, int & strength, int & speed, int & magic) {
vector<string> tokens = tokenize(input);
vector<string> tokens2 = tokenize(input, ".");
if (tokens.size() != 6 or tokens2.size() > 1) {
return false;
}
name = tokens[0];
string parsed_type = tokens[1];
if(parsed_type.size() != 1) {
return false;
}
if (not ( parsed_type == "A"
or parsed_type == "C"
or parsed_type == "R")) {
return false;
}
type = parsed_type;
int parsed_max_hp = atoi(tokens[2].c_str());
int parsed_strength = atoi(tokens[3].c_str());
int parsed_speed = atoi(tokens[4].c_str());
int parsed_magic = atoi(tokens[5].c_str());
if (parsed_max_hp == 0 or parsed_strength == 0 or parsed_speed == 0 or
parsed_magic == 0) {
return false;
}
max_hp = parsed_max_hp;
strength = parsed_strength;
speed = parsed_speed;
magic = parsed_magic;
return true;
}