困惑如何在 C++ 中使用 strtod() 从字符串转换为双精度;

发布于 2024-11-01 18:26:32 字数 45 浏览 6 评论 0原文

如果有人能解释如何使用该功能,那就太好了。看不懂参数。

谢谢

If someone could explain how to use the function, that would be great. I don't understand the parameters.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最美的太阳 2024-11-08 18:26:32

第一个参数是指向字符的指针。 c_str() 为您提供来自字符串对象的指针。第二个参数是可选的。它将包含一个指向字符串中数值之后的下一个字符的指针。请参阅http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/< /a> 了解更多信息。

string s;
double d;

d = strtod(s.c_str(), NULL);

First parameter is a pointer to the chars. c_str() gives you that pointer from a string object. Second parameter is optional. It would contain a pointer to the next char after the numerical value in the string. See http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/ for more infos.

string s;
double d;

d = strtod(s.c_str(), NULL);
烟若柳尘 2024-11-08 18:26:32

第一个参数是要转换的字符串,第二个参数是对 char* 的引用,您想要指向原始字符串中 float 后面的第一个字符(如果您想在数字)。如果您不关心第二个参数,可以将其设置为 NULL。

例如,如果我们有以下变量:

char* foo = "3.14 is the value of pi"
float pi;
char* after;

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 都指向同一个数组。

The first argument is a the string you want to convert, the second argument is a reference to a char* that you want to point to the first char after the float in your original string (in case you want to start reading the string after the number). If you do not care about the second argument, you can set it to NULL.

For example, if we have the following variables:

char* foo = "3.14 is the value of pi"
float pi;
char* after;

After pi = strtod(foo, after) the values are going to be:

foo is "3.14 is the value of pi"
pi is 3.14f
after is " is the value of pi"

Note that both foo and after are pointing to the same array.

紫竹語嫣☆ 2024-11-08 18:26:32

如果您使用 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; }

If you're working in C++, then why don't you use std::stringstream?

std::stringstream ss("78.987");

double d;
ss >> d;

Or, even better boost::lexical_cast as:

double d;
try
{
    d = boost::lexical_cast<double>("889.978");
}
catch(...) { std::cout << "string was not a double" << std::endl; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文