将字符串(以char*形式给出)解析为int的C++方式是什么?强大而清晰的错误处理是一个优点(而不是返回零).
我在 C++ 中看到了很多将字符串转换为数字的选项。
其中一些实际上建议使用标准 C 函数,例如atoi和atof。
我还没有看到有人建议使用以下选项,该选项仅依赖于 C++ STL:
int Str2Num(const string& str) // can be called with a 'char*' argument as well
{
int num;
istringstream(str)>>num;
return num;
}
Run Code Online (Sandbox Code Playgroud)
或者更一般地说:
template <typename type>
type Str2Num(const string& str) // can be called with a 'char*' argument as well
{
type num;
istringstream(str)>>num;
return num;
}
Run Code Online (Sandbox Code Playgroud)
上述实现有哪些缺点?
有没有更简单/更干净的方法来实现这种转换?