Warm tip: This article is reproduced from stackoverflow.com, please click
c++

Version of std::stoi rejecting any non-number

发布于 2020-03-28 23:16:10

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)?

Questioner
bartop
Viewed
21
NutCracker 2020-01-31 18:22

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