用C ++简单的字符串解析 [英] Simple string parsing with C++
问题描述
我一直在使用C ++很长一段时间,但是当我必须解析简单的文本文件时,我倾向于回退 scanf
。例如给定这样的配置(也假设字段的顺序可以变化):
foo:[3 4 5 ]
baz:3.0
我会这样写:
char行[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 ::字符串令牌;
while(std :: getline(iss,token,','))
{
std :: cout<令牌< std :: endl;
}
}
if(result ==bar)
{
// ...
}
}
I've been using C++ for quite a long time now but nevertheless I tend to fall back on scanf
when I have to parse simple text files. For example given a config like this (also assuming that the order of the fields could vary):
foo: [3 4 5]
baz: 3.0
I would write something like:
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;
}
}
What's the most concise way to achieve this in C++? Whenever I try I end up with a lot of scaffolding code.
This is a try using only standard C++.
Most of the time I use a combination of std::istringstream and std::getline (which can work to separate words) to get what I want. And if I can I make my config files look like:
foo=1,2,3,4
which makes it easy.
text file is like this:
foo=1,2,3,4
bar=0
And you parse it like this:
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 ++简单的字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!