#include <stdlib.h>
....
double returnDistance(string coord1, string coord2, const vector<string> vec) {
int arr1[11], arr2[11];
istringstream iss1(coord1);
int i = 0;
while(iss1) {
iss1 >> arr1[i];
i++;
}
istringstream iss2(coord2);
i = 0;
while(iss2) {
iss2 >> arr2[i];
i++;
}
//error below when calling atof
return calculateDistance(atof(arr1[6]), atof(arr2[6]),
atof(arr1[7]), atof(arr2[7]),
atof(arr1[8]), atof(arr2[8]))
}arr1[]和arr2[]都是字符串数组,calculateDistance会在给定x,y,z坐标的情况下计算3-D距离,但由于某种原因,我得到的错误是“没有匹配的函数调用'atof'”。请帮帮我!
PS:当我尝试使用.c_str()时,我得到以下错误:“成员引用基类型'int‘不是一个结构或联合”
发布于 2013-11-10 09:19:09
如果我理解你代码的目标,你应该按如下方式更新它:
double arr1[11], arr2[11];
...
return calculateDistance(arr1[6], arr2[6],
arr1[7], arr2[7],
arr1[8], arr2[8]);基本上,每个arr?[?]都已经是一个浮点数,字符串->浮点数的转换是由>>操作符完成的。
发布于 2013-11-10 09:19:31
函数atof()用于将ASCII (C样式字符串)转换为double。您传递的是整数;不会有重载。
您可以简单地使用强制转换(static_cast<double>(arr1[0])等),尽管您也可以使用整数来调用函数。或者,您可以提供一个简单的内联函数来执行转换:
inline double itof(int i) { return i; }我只是错误地将数组声明为
而不是string。
但是为什么不将数组声明为double呢?并检查数组边界:
#include <vector>
#include <strstream>
#include <string>
using namespace std;
extern double calculateDistance(double x1, double y1, double x2, double y2, double x3, double y3);
double returnDistance(string coord1, string coord2, const vector<string> vec);
double returnDistance(string coord1, string coord2, const vector<string>)
{
vector<double> arr1, arr2;
istringstream iss1(coord1);
int i1 = 0;
while (iss1 && i1 < 9) // No need to read beyond 9th number
iss1 >> arr1[i1++];
istringstream iss2(coord2);
int i2 = 0;
while (iss2 && i2 < 9) // No need to read beyond 9th number
iss2 >> arr2[i2++];
if (i1 != i2 || i1 < 9)
return 0.0;
return calculateDistance(arr1[6], arr2[6], arr1[7], arr2[7], arr1[8], arr2[8]);
}这段代码编译得很干净。请注意,main函数的const vector<string>参数未使用,因此在函数定义中未命名。
https://stackoverflow.com/questions/19885049
复制相似问题