I have a program that's expected to take as input a few options to specify probabilities in the form (p1, p2, p3, ... ). So the command line usage would literally be:
./myprog -dist (0.20, 0.40, 0.40)
I want to parse lists like this in C++ and I am currently trying to do it with iterators for the std::string type and the split function provided by Boost.
// Assume stuff up here is OK std::vector<string> dist_strs; // Will hold the stuff that is split by boost. std::string tmp1(argv[k+1]); // Assign the parentheses enclosed list into this std::string. // Do some error checking here to make sure tmp1 is valid. boost::split(dist_strs, <what to put here?> , boost::is_any_of(", "));
Note above the <what to put here?>
part. Since I need to ignore the beginning and ending parentheses, I want to do something like
tmp1.substr( ++tmp1.begin(), --tmp1.end() )
but it doesn't look like substr
works this way, and I cannot find a function in the documentation that works to do this.
One idea I had was to do iterator arithmetic, if this is permitted, and use substr
to call
tmp1.substr( ++tmp1.begin(), (--tmp1.end()) - (++tmp1.begin()) )
but I wasn't sure if this is allowed, or if it is a reasonable way to do it. If this isn't a valid approach, what is a better one? ...Many thanks in advance.
Substring in C++ A function to obtain a substring in C++ is substr(). This function contains two parameters: pos and len. The pos parameter specifies the start position of the substring and len denotes the number of characters in a substring.
we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.
Copying one string to another - strcpyYou must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy . The source character array is the second parameter to strcpy .
std::substr() is a C++ method that's used to manipulate text to store a specific part of string. In short, it “extracts” a string from within a string.
std::string
's constructor should provide the functionality you need.
std::string(tmp1.begin() + 1, tmp1.end() - 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With