将子字符串从输入文件转换为双精度值? 以上是我目前正在为一个初学者C++课程所做的一个项目的摘录。我正在从输入文件中读取此字符串: void getBaseCoord(string droneInfo, double& x, double& y, double& z){ // x= stod(droneInfo.substr(31, 3)); //y= stod(droneInfo.substr(34, 3)); // z= stod(droneInfo.substr(37, 3)); string strx, stry, strz; strx = droneInfo.substr(31, 3); stry = droneInfo.substr(34, 3); strz = droneInfo.substr(37,3); x = stof(strx); y = stof(stry); z = stof(strz);
注释掉的部分是为了函数操作的目的,试图将字符串行中的子字符串转换为双精度值。但是,我无法以这种方式转换它们,在编译时我得到了一个错误,即未声明将子字符串从输入文件转换为双精度值? 以上是我目前正在为一个初学者C++课程所做的一个项目的摘录。我正在从输入文件中读取此字符串: void getBaseCoord(string droneInfo, double& x, double& y, double& z){ // x= stod(droneInfo.substr(31, 3)); //y= stod(droneInfo.substr(34, 3)); // z= stod(droneInfo.substr(37, 3)); string strx, stry, strz; strx = droneInfo.substr(31, 3); stry = droneInfo.substr(34, 3); strz = droneInfo.substr(37,3); x = stof(strx); y = stof(stry); z = stof(strz);,c++,c++11,C++,C++11,注释掉的部分是为了函数操作的目的,试图将字符串行中的子字符串转换为双精度值。但是,我无法以这种方式转换它们,在编译时我得到了一个错误,即未声明stod(我猜它认为这是一个变量?) 在一个函数中将子字符串转换为双值的正确方法是什么?不确定stod()是什么,但它高度暗示了哪个函数正好执行该操作 请注意,该函数有两个参数,尽管第二个参数可能为NULL。第一个参数是C样式的字符串,因此可能需要进行转换: 9673767892DroaninAlong4880021DO4.37.33.88.19.33.8
stod
(我猜它认为这是一个变量?)
在一个函数中将子字符串转换为双值的正确方法是什么?不确定stod()是什么,但它高度暗示了哪个函数正好执行该操作
请注意,该函数有两个参数,尽管第二个参数可能为NULL。第一个参数是C样式的字符串,因此可能需要进行转换:
9673767892DroaninAlong4880021DO4.37.33.88.19.33.8U
不确定stod()是什么,但它高度暗示了到底是哪个执行该操作
请注意,该函数有两个参数,尽管第二个参数可能为NULL。第一个参数是C样式的字符串,因此可能需要进行转换:
9673767892DroaninAlong4880021DO4.37.33.88.19.33.8U
或者,您可以使用
stringstream
类。您可以这样使用它:
void getBaseCoord(string droneInfo, double& x, double& y, double& z)
{
x = strtod(droneInfo.substr(31, 3).cstr(), NULL);
y = strtod(droneInfo.substr(34, 3).cstr(), NULL);
z = strtod(droneInfo.substr(37, 3).cstr(), NULL);
}
std::string strx=droneInfo.substr(31,3);
双x;
std::stringstream-ss;
ss>x;
请记住添加
#包含,以使此解决方案正常工作,如果要重用stringstream对象,请将其添加到.clear()
。您可以看到完整的示例。或者,您可以使用stringstream
类。您可以这样使用它:
void getBaseCoord(string droneInfo, double& x, double& y, double& z)
{
x = strtod(droneInfo.substr(31, 3).cstr(), NULL);
y = strtod(droneInfo.substr(34, 3).cstr(), NULL);
z = strtod(droneInfo.substr(37, 3).cstr(), NULL);
}
std::string strx=droneInfo.substr(31,3);
双x;
std::stringstream-ss;
ss>x;
请记住添加#包含,以使此解决方案正常工作,如果要重用stringstream对象,请将其添加到.clear()
。您可以看到完整的示例。std::stod
是用于将字符串转换为双精度字符串的c++11
函数。还有stof
,stold
,stoi
,stol
,stoul
,stoull
,float
,long double
,integer
,long
,long
,unsigned long
,long
,和unsigned long long
。std::stod
是用于将字符串转换为双精度字符串的c++11
函数。还有stof
,stold
,stoi
,stol
,stoul
,stoull
,float
,long double
,integer
,long
,long
,unsigned long
,long
,和无符号long-long
。您必须#包括。如果您没有通过使用名称空间std拉入标准库
必须在调用前加上std::
前缀,如下所示:std::stod(droneInfo.substr(31,3))代码>您必须#包括
。如果您没有通过使用名称空间std拉入标准库
必须在调用前加上std::
前缀,如下所示:std::stod(droneInfo.substr(31,3))代码>