1

I have strings like this

10z45
9999i4a

Basically int-char-int-optionalchar

I want to do this function prototype

void process(std::string input, int &first, char &c, int &last, bool &optional)

Only thing is I'm not sure the best way to iterate over the string to extract these values. Would rather not use regex library, seems like can be done simply?

2
  • 1
    On an aesthetic note, I tend to feel that if a function has "return values" it really should be the case that they are a return value from the function instead of parameters by reference. Why not make a structure/class to represent this decoding, and return a value of that type? Commented Oct 12, 2012 at 0:57
  • I agree. A structure is a better fit here. Commented Oct 12, 2012 at 0:57

2 Answers 2

3

Use a string stream:

#include <sstream>
...
std::istringstream iss(input);
iss >> first >> c >> last >> optional;

If there's no final character, the value of optional won't be touched, so I'd recommend setting it to 0 beforehand.

Sign up to request clarification or add additional context in comments.

Comments

1

Use std::istringstream, read int, char, int, then try next char:

std::istringstream is(input);
is >> first >> c >> last;
char c2;
optional = (is >> c2);

I'm not sure this is 100% what you want -but I'd do it in this way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.