我与某人谈论了垮台事件std::stoi.坦率地说,它在std::strtol内部使用,如果报告错误则抛出.但是,根据他们的说法,std::strtol不应该为输入报告错误"abcxyz",导致stoi不抛出std::invalid_argument.
首先,这里有两个在GCC上测试过的关于这些案例行为的程序:
strtol
stoi
他们都表现出成功"123"和失败"abc".
我查看标准以获取更多信息:
§21.5
Throws: invalid_argument if strtol, strtoul, strtoll, or strtoull reports that
no conversion could be performed. Throws out_of_range if the converted value is
outside the range of representable values for the return type.
Run Code Online (Sandbox Code Playgroud)
总结了依赖的行为strtol.那怎么样strtol?我在C11草案中找到了这个:
§7.22.1.4
If the subject sequence is empty or does not have the expected form, no
conversion is performed; the value …Run Code Online (Sandbox Code Playgroud) 我正在参与挑战,只是为了切入点,在我的程序中的一个地方我需要将字符串转换为整数.我已经尝试过boost :: lexical_cast,但不幸的是它是sooo sloowwww.我想因为它执行的所有检查.我需要的是能够在没有任何检查的情况下执行此转换的内容(我知道将有效数字存储为字符串).顺便使用stringstream以天真的方式:
stringstream interpreter;
interpreter << str;
interpreter >> number;
Run Code Online (Sandbox Code Playgroud)
甚至比boost :: lexical_cast慢.
atoi是唯一的选择吗?