The easiest way to read formatted input in C++?

后端 未结 4 961
醉酒成梦
醉酒成梦 2021-01-17 08:37

Is there any way to read a formatted string like this, for example :48754+7812=Abcs.

Let\'s say I have three stringz X,Y and Z, and I want



        
4条回答
  •  [愿得一人]
    2021-01-17 09:12

    A possibility is boost::split(), which allows the specification of multiple delimiters and does not require prior knowledge of the size of the input:

    #include 
    #include 
    #include 
    
    #include 
    #include 
    
    int main()
    {
        std::vector tokens;
        std::string s(":48754+7812=Abcs");
        boost::split(tokens, s, boost::is_any_of(":+="));
    
        // "48754" == tokens[0]
        // "7812"  == tokens[1]
        // "Abcs"  == tokens[2]
    
        return 0;
    }
    

    Or, using sscanf():

    #include 
    #include 
    
    int main()
    {
        const char* s = ":48754+7812=Abcs";
        int X, Y;
        char Z[100];
    
        if (3 == std::sscanf(s, ":%d+%d=%99s", &X, &Y, Z))
        {
            std::cout << "X=" << X << "\n";
            std::cout << "Y=" << Y << "\n";
            std::cout << "Z=" << Z << "\n";
        }
    
        return 0;
    }
    

    However, the limitiation here is that the maximum length of the string (Z) must be decided before parsing the input.

提交回复
热议问题