Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing String to Array of Integers

I'm looking for a way to convert a string with specified dividers (such as slashes or spaces) into an array of the integers those dividers separate.

For example, if the user inputs 12/3/875/256, I need to retrieve the array {12, 3, 875, 256}. Ideally, it would be able to handle an arbitrary length.

I tried sweeping through the string character-by-character and storing everything that's not a divider in a temporary variable, which is added to the array the next time I encounter a divider character. Unfortunately, the type conversions are being a pain in the butt. Is there an easier way to do this?

like image 958
Maxpm Avatar asked Nov 29 '25 17:11

Maxpm


2 Answers

You can set '/' to a delimiter and read using getline? then you'd have to put each one into a variable, and you'd need to know the size--maybe you can pass over the array and count the slashes? then you'd know that and can set up the array first. You might need to parse each string segment into an int, which may or may not be difficult. (haven't used c++ for a while, I don't remember a convenient way.)

See here for a small example of how this is done (3 posts down).

like image 184
Jan Gorzny Avatar answered Dec 02 '25 06:12

Jan Gorzny


Try using the boost::tokenizer and boost::lexical_cast

like image 20
yasouser Avatar answered Dec 02 '25 08:12

yasouser