[英]Converting a string to a number in C++
I'm seeing a lot of options for converting a string to a number in C++.我看到了很多在 C++ 中将字符串转换为数字的选项。
Some of which are actually recommending the use of standard C functions such as atoi
and atof
.其中一些实际上是推荐使用标准 C 函数,例如
atoi
和atof
。
I have not seen anyone suggesting the following option, which relies solely on C++ STL:我没有看到有人建议以下选项,它完全依赖于 C++ STL:
int Str2Num(const string& str) // can be called with a 'char*' argument as well
{
int num;
istringstream(str)>>num;
return num;
}
Or more generally:或更一般地说:
template <typename type>
type Str2Num(const string& str) // can be called with a 'char*' argument as well
{
type num;
istringstream(str)>>num;
return num;
}
What are the disadvantages in the above implementation?上述实现的缺点是什么?
Is there a simpler / cleaner way to achieve this conversion?是否有更简单/更清洁的方法来实现这种转换?
In c++11 there's a number of numeric conversion functions defined in the std::string
class itself:在c++11中,
std::string
类本身定义了许多数值转换函数:
Numeric conversions
数值转换
stoi (C++11)标准 (C++11)
stol (C++11)斯托尔 (C++11)
stoll (C++11)斯托尔 (C++11)
converts a string to a signed integer
将字符串转换为有符号整数
stoul (C++11)
斯托尔 (C++11)
stoull (C++11)斯托尔 (C++11)
converts a string to an unsigned integer
将字符串转换为无符号整数
stof (C++11)
存储 (C++11)
stod (C++11)标准 (C++11)
stold (C++11)出售 (C++11)
converts a string to a floating point value
将字符串转换为浮点值
As for pre c++11 standards, I can't see any disadvantages from your template function sample.至于 c++11 之前的标准,我从您的模板函数示例中看不到任何缺点。
你可以使用转换函数 Strtol() Strtoul() 但是在 C++11 中,你已经得到了上面的答案。
#include <sstream>
template <typename T>
inline bool StringToNumber(const std::string& sString, T &tX)
{
std::istringstream iStream(sString);
return !(iStream >> tX).fail();not
}
Then call然后打电话
double num{};
StringToNumber(std::string{"580.8"}, num);
float fnum{};
StringToNumber(std::string{"5e+1.0"}, fnum);
#include <iostream> #include <string> int main() { std::string str = "123"; int num; // using stoi() to store the value of str1 to x num = std::stoi(str); std::cout << num; return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.