Reputation: 10315
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)?
Upvotes: 4
Views: 654
Reputation: 12263
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
Upvotes: 2
Reputation: 1072
Doesn't the second argument suite you? Second argument of std::stoi is very usefull for that: if returned position is equills the size of the string then whole string is a number.
Upvotes: 1
Reputation: 609
The second argument of std::sto*()
methods is std::size_t * pos
which will be set to the number of numeric characters used for the conversion (can be seen here).
This is how I implemented this:
int my_stoi(const std::string & str)
{
std::string::size_type pos;
const int value = std::stoi(str, /* out */ &pos);
if (pos != str.size())
{
std::cerr << "Failed parsing string '" << str << "' as an integer" << std::endl;
}
return value;
}
Upvotes: 1