std::stoi - 具有非数字字符的字符串被解析为整数而不抛出异常 (c++)

std::stoi - String with non-numeric characters getting parsed as an integer without throwing exception (c++)

当使用 std::stoi 并传递以数字开头且后跟非数字字符的字符串时,该字符串被成功解析为整数,而不会引发异常。 例如“0abcf”被解析为 0。 我希望仅当字符串仅包含数字字符(即“123”而不是“12a”)时才将其解析为整数,是否存在执行此操作的现有函数?

引用自documentation

int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
...
the index of [the first unconverted] character will be calculated and stored in *pos, giving the number of characters that were processed by the conversion.

因此,为了检查是否所有字符都是 valid/parsed,您需要做的就是传递第二个参数,然后检查这个值(转换后的字符数)是否等于字符串中的字符。