Search code examples
c++inputformatted

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


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

X = 48754 
Y = 7812
Z = Abcs

The size of the two numbers and the length of the string may vary, so I dont want to use substring() or anything like that.

Is it possible to give C++ a parameter like this

":#####..+####..=SSS.."

so it knows directly what's going on?


Solution

  • 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 <iostream>
    #include <vector>
    #include <string>
    
    #include <boost/algorithm/string.hpp>
    #include <boost/algorithm/string/split.hpp>
    
    int main()
    {
        std::vector<std::string> 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 <iostream>
    #include <cstdio>
    
    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.