Simple string parsing with C++

前端 未结 6 1084
感情败类
感情败类 2020-12-04 10:22

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

6条回答
  •  悲哀的现实
    2020-12-04 11:07

    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" )
                {
                   //...
        }
    }
    

提交回复
热议问题