Try this using C++11 std::stoi
:
char c_str[] = "[51,53]";
std::string s(c_str);
int num1 = std::stoi(s.substr(1, 2));
int num2 = std::stoi(s.substr(4, 2));
If you know the numbers will be outside the range 10-99
then use this instead:
char c_str[] = "[5156789,5]";
std::string s(c_str);
s.assign(s.substr(1, s.size() - 2)); // Trim away '[' and ']'
std::string::size_type middle = s.find(','); // Find position of ','
int num1 = std::stoi(s.substr(0, middle));
int num2 = std::stoi(s.substr(middle + 1, s.size() - (middle + 1)));
The function stoi
will throw std::invalid_argument
if number can't be parsed.
Edit:
For a more rubust solution that will only parse base-10 numbers, you should use something like this:
char c_str[] = "[51,0324]";
int num1, num2;
try {
std::string s(c_str);
s.assign(s.substr(1, s.size() - 2));
std::string::size_type middle = s.find(',');
std::unique_ptr<std::size_t> pos{new std::size_t};
std::string numText1 = s.substr(0, middle);
num1 = std::stoi(numText1, pos.get()); // Try parsing first number.
if (*pos < numText1.size()) {
throw std::invalid_argument{{numText1.at(*pos)}};
}
std::string numText2 = s.substr(middle + 1, s.size() - (middle + 1));
num2 = std::stoi(numText2, pos.get()); // Try parsing second number.
if (*pos < numText2.size()) {
throw std::invalid_argument{{numText2.at(*pos)}};
}
} catch (const std::invalid_argument& e) {
std::cerr << "Could not parse number" << std::endl;
std::exit(EXIT_FAILURE);
}
It will throw std::invalid_argument
when trying to parse strings as "1337h4x0r"
and such, unlike when using std::istringstream
. Se this for more info