Confused how to convert from a string to double using strtod() in C++

落花浮王杯 提交于 2019-12-01 10:38:26

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);

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.

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; }

I don't understand the parameters.

Check this link strtod. Provides all information with example.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!