困惑如何在c++中使用strtod()从字符串转换为双精度
Confused how to convert from a string to double using strtod() in C++
如果有人能解释一下如何使用这个函数,那就太好了。我看不懂这些参数。
谢谢
第一个形参是指向字符的指针。C_str()为您提供来自字符串对象的指针。第二个参数是可选的。它将包含一个指针,指向字符串中数值后面的下一个字符。更多信息请参见http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/。
string s;
double d;
d = strtod(s.c_str(), NULL);
第一个参数是你想要转换的字符串,第二个参数是对char*的引用,你想要指向原始字符串中浮点数之后的第一个字符(以防你想要开始读取数字后的字符串)。如果您不关心第二个参数,则可以将其设置为NULL。
例如,如果我们有以下变量:
char* foo = "3.14 is the value of pi"
float pi;
char* after;
在pi = strtod(foo, after)
之后的值将是:
foo is "3.14 is the value of pi"
pi is 3.14f
after is " is the value of pi"
注意foo和after都指向同一个数组
如果你在c++中工作,那么为什么不使用std::stringstream
呢?
std::stringstream ss("78.987");
double d;
ss >> d;
或者,更好的boost::lexical_cast
为:
double d;
try
{
d = boost::lexical_cast<double>("889.978");
}
catch(...) { std::cout << "string was not a double" << std::endl; }
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组