您可以使用C ++ 17 std::from_chars
并检查解析值的长度:
#include <iostream>
#include <charconv>
int main() {
const std::string str { "123haha" };
int value = 0;
const auto result = std::from_chars(str.data(),
str.data() + str.size(),
value);
if (result.ec == std::errc()) {
std::cout << "Value: " << value << std::endl;
std::cout << "Length: " << result.ptr - str.data() << std::endl;
}
return 0;
}
现场查看
C ++ 11解决方案
的第二个参数std::stoi
是整数的地址,用于存储处理的字符数。
#include <iostream>
int main() {
const std::string str { "123haha" };
std::size_t processed_chars = 0;
int value = std::stoi(str, &processed_chars);
std::cout << "Value: " << value << std::endl;
std::cout << "Length: " << processed_chars << std::endl;
return 0;
}
现场查看
我喜欢这个答案,但我还没有C ++ 17 :(
@bartop我也将尝试写答案的C ++ 11部分