使用 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));
如果您知道数字将超出范围,请10-99
改用:
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)));
如果无法解析数字,该函数stoi
将抛出。std::invalid_argument
编辑:
对于只会解析以 10 为底的数字的更强大的解决方案,您应该使用以下内容:
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);
}
std::invalid_argument
它会在尝试解析字符串时抛出"1337h4x0r"
,这与使用std::istringstream
. 了解更多信息