Assuming my program expects arguments of the form [ 0.562 , 1.4e-2 ] (ie pairs of floats), how should I parse this input in C ++ without regular expressions? I know that there are many angular cases to consider when it comes to user input, but let's assume that this input closely matches the above format (except for additional spaces).
In C, I could do something like sscanf(string, "[%g , %g]", &f1, &f2); to extract two floating point values, which is very compact.
In C ++, this is what I came up with so far:
std::string s = "[ 0.562 , 1.4e-2 ]"; // example input float f1 = 0.0f, f2 = 0.0f; size_t leftBound = s.find('[', 0) + 1; size_t count = s.find(']', leftBound) - leftBound; std::istringstream ss(s.substr(leftBound, count)); string garbage; ss >> f1 >> garbage >> f2; if(!ss) std::cout << "Error while parsing" << std::endl;
How can I improve this code? In particular, I am associated with the garbage string, but I donβt know how else to skip between these two values.
c ++ parsing scanf
ph4nt0m
source share