As you may know, std::sto*
function family works in a way that reads number in string until it finds non-number, like that:
std::string pseudoNum = "123haha";
int num = std::stoi(pseudoNum); //no problem, num = 123
Is there any standard way to have more strict integer parsing, which causes exception/error code return in such situations (when string is not completely integer)?
You can use C++17's std::from_chars
and check the length of the parsed value:
#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;
}
Check it out live
C++11 solution
A second parameter to std::stoi
is an address of an integer to store the number of characters processed.
#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;
}
Check it out live
as much as I like this answer, I don't have C++17 yet :(
@bartop I will try to write a C++11 part of the answer too