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

后端 未结 4 978
醉酒成梦
醉酒成梦 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:01

    for example.

    #include 
    #include 
    
    int main()
    {
       boost::regex re("\":(\\d+)\\+(\\d+)=(.+)\"");
       std::string example = "\":48754+7812=Abcs\"";
       boost::smatch match;
       if (boost::regex_match(example, match, re))
       {
          std::cout << "f number: " << match[1] << " s number: " << match[2] << " string: " << match[3]
          << std::endl;
       }
       else
       {
          std::cout << "not match" << std::endl;
       }
    }
    

    and second variant, work only with string.

    #include 
    #include 
    
    int main()
    {
       std::string s = "\":48754+7812=Abcs\"";
       std::string::size_type idx = s.find(":");
       std::string::size_type end_first = s.find("+", idx + 1);
       std::string f_number = s.substr(idx + 1, end_first - (idx + 1));
       std::cout << f_number << std::endl;
       std::string::size_type end_second = s.find("=", end_first + 1);
       std::string s_number = s.substr(end_first + 1, end_second - (end_first + 1));
       std::cout << s_number << std::endl;
       std::string::size_type string_end = s.find("\"", end_second);
       std::string str = s.substr(end_second + 1, string_end - (end_second + 1));
       std::cout << str << std::endl;
    }
    

提交回复
热议问题