我正在尝试创建一个简单的解析器和一个遵循以下结构的小文本文件:
Variable_name = Value;
VARIABLE_2 = SECOND_VALUE;
找到了可行的方法,但是,使用了许多库,例如 Boost。我想知道您是否可以制作一个简单的,最好只使用 STD 的库。
谢谢,布鲁诺·阿拉诺。
最佳答案
如果您的格式与您列出的一样,并且变量名称或值中没有空格,则可以使用 std::string
的组合轻松完成和 std::istringstream
。您可以简单地执行以下操作:
//assume we have an open ifstream object called in_file to your file
string line;
getline(in_file, line);
while (in_file.good())
{
char variable[100];
char value[100];
char equals;
//get rid of the semi-colon at the end of the line
string temp_line = line.substr(0, line.find_last_of(";"));
istringstream split_line(temp_line);
//make sure to set the maximum width to prevent buffer overflows
split_line >> setw(100) >> variable >> equals >> value;
//do something with the string data in your buffers
getline(in_file, line);
}
您可以更改variable
和value
的类型以适本地满足您的需要...它们不需要是char
缓冲区,但可以是任何其他类型,前提是 istream& operator>>(istream&, type&)
是为您要使用的数据类型定义的。
关于c++ - 简单解析器的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030861/