我已经使用 C++ 很长时间了,但是当我必须解析简单的文本文件时,我倾向于使用 scanf
。例如,给定这样的配置(还假设字段的顺序可能会有所不同):
foo: [3 4 5]
baz: 3.0
我会写这样的:
char line[SOME_SIZE];
while (fgets(line, SOME_SIZE, file)) {
int x, y, z;
if (3 == sscanf(line, "foo: [%d %d %d]", &x, &y, &z)) {
continue;
}
float w;
if (1 == sscanf(line, "baz: %f", &w)) {
continue;
}
}
在 C++ 中实现此目的最简洁的方法是什么?每当我尝试时,我都会得到很多脚手架代码。
最佳答案
这是一个仅使用标准 C++ 的尝试。
大多数时候我结合使用 std::istringstream 和 std::getline (可以用来分隔单词)来获得我想要的东西。如果可以的话,我可以让我的配置文件看起来像:
foo=1,2,3,4
这很容易。
文本文件是这样的:
foo=1,2,3,4
bar=0
然后你像这样解析它:
int main()
{
std::ifstream file( "sample.txt" );
std::string line;
while( std::getline( file, line ) )
{
std::istringstream iss( line );
std::string result;
if( std::getline( iss, result , '=') )
{
if( result == "foo" )
{
std::string token;
while( std::getline( iss, token, ',' ) )
{
std::cout << token << std::endl;
}
}
if( result == "bar" )
{
//...
}
}
关于c++ - 使用 C++ 进行简单的字符串解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2880903/