See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Parsing string in C++ with brackets

General Tech Bugs & Fixes
Max. 2000 characters

Vikrant Srivastava


( 7 months ago )

I have to parse string in C++ to get doubles out of it. String is in format like [(a,b)-(c,d)], where a, b, c and d are going to be double variables.

I was trying to use stringstrem, but it doesn't accept const char argument, so I have no idea right now how to solve it.

My code right now looks like:

ss >> "[(" >> a >> "," >> b >> ")-(" >> c >> "," >> d >> ")]";

But sadly it doesnt work :(

For example: [(1.2,3.4)-(6.5,7.4)]. And I want:


Vikrant Srivastava


( 7 months ago )

With input streams, you need to read input to a variable. You could read into a char or into a string with std::istream::read. Ideally you would check the characters are actually as expected, to catch and probably reject say __1.2-3.4@#~6.5,7.8++

char chr;
ss >> chr >> chr >> a >> chr >> b >> chr >> chr >> chr >> c >> chr >> d >> chr >> chr;

Alternatively you might read it as a string, and then you can use the C++ <regex> functionality to match it, perhaps something like:


This will give you 4 capture groups on success, which you can then convert to doubles. You can modify this if for example extra spaces are allowed, the decimal point is optional, etc.

If there is any variation in the format at all, for example sometimes you get 3 numbers, e.g. [(1.2,3.4)-(6.5,7.4)+(1.5,2)] you would need to do more in depth parsing than the >> operator can directly support.

Possibly with logic based on what ss >> chr read, or by looping on a regex based on where the previous match ended (instead of matching the entire string at once) although things get a lot more advanced.

what's your interest