我有以下文件/行:
pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200
Run Code Online (Sandbox Code Playgroud)
等等.我希望解析它并获取键值对并将它们放在一个结构中:
struct pky
{
pky() :
a_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fr(0),
g('U'),
a(0),
pc(0),
p_id(0)
{ }
};
Run Code Online (Sandbox Code Playgroud)
其中,可以使用所有结构字段,也可以省略一些结构字段.
如何创建一个C++类,它会做同样的事情?我是C++的新手,并不知道任何可以完成这项工作的函数或库.
每行都要进行处理,每次使用一行并填充结构,然后再刷新.该结构稍后用作函数的参数.
Joh*_*itb 10
你可以这样做:
std::string line;
std::map<std::string, std::string> props;
std::ifstream file("foo.txt");
while(std::getline(file, line)) {
std::string token;
std::istringstream tokens(line);
while(tokens >> token) {
std::size_t pos = token.find('=');
if(pos != std::string::npos) {
props[token.substr(0, pos)] = token.substr(pos + 1);
}
}
/* work with those keys/values by doing properties["name"] */
Line l(props["pc"], props["ct"], ...);
/* clear the map for the next line */
props.clear();
}
Run Code Online (Sandbox Code Playgroud)
我希望它有用.线可以是这样的:
struct Line {
std::string pc, ct;
Line(std::string const& pc, std::string const& ct):pc(pc), ct(ct) {
}
};
Run Code Online (Sandbox Code Playgroud)
现在只有在分隔符是空格时才有效.你也可以使它与其他分隔符一起使用.更改
while(tokens >> token) {
Run Code Online (Sandbox Code Playgroud)
例如,如果您想要一个分号,请执行以下操作:
while(std::getline(tokens, token, ';')) {
Run Code Online (Sandbox Code Playgroud)
实际上,看起来你只有整数作为值,而空白作为分隔符.你可能想改变
std::string token;
std::istringstream tokens(line);
while(tokens >> token) {
std::size_t pos = token.find('=');
if(pos != std::string::npos) {
props[token.substr(0, pos)] = token.substr(pos + 1);
}
}
Run Code Online (Sandbox Code Playgroud)
进入这个:
int value;
std::string key;
std::istringstream tokens(line);
while(tokens >> std::ws && std::getline(tokens, key, '=') &&
tokens >> std::ws >> value) {
props[key] = value;
}
Run Code Online (Sandbox Code Playgroud)
std::ws只是吃空白.你应该改变道具的类型
std::map<std::string, int> props;
Run Code Online (Sandbox Code Playgroud)
然后,让Line接受int而不是std :: string.我希望这不是一次太多的信息.