The easiest way to read formatted input in C++? -
is there way read formatted string this, example :48754+7812=abcs
.
let's have 3 stringz x,y , z, , want
x = 48754 y = 7812 z = abcs
the size of 2 numbers , length of string may vary, dont want use substring()
or that.
is possible give c++ parameter this
":#####..+####..=sss.."
so knows directly what's going on?
a possibility boost::split()
, allows specification of multiple delimiters , not require prior knowledge of size of 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, limitiation here maximum length of string (z
) must decided before parsing input.
Comments
Post a Comment