我试图创建一个可以用作矢量的矢量对象。但是,我输入有问题。我想格式化输入,以便我可以输入3.4i+5.4j-8.4k
,它会将值相应地放入类中的正确变量。
班级:
class Vector3D
{
public:
Vector3D(double xA, double yA, double zA);
Vector3D(Points &terminate, Points &start);
Vector3D(const Vector3D &vec);
Vector3D();
double vector_length();
float compute_hor_angle();
float compute_vert_angle();
float get_hor_angle();
float get_vert_angle();
double get_length();
friend ostream& operator <<(ostream& out,const Vector3D& vec);
istream& operator >>(istream& in, Vector3D& vec);
private:
double x;
double y;
double z;
double length;
float angle_hor;
float angle_vert;
};
我的尝试:
istream& Vector3D::operator >>(istream& in, Vector3D& vec)
{
char charecter, x,y,z;
in >> vec.x >> x;
in >> charecter;
if(charecter == '-')
{
in >> vec.y >> y;
vec.y = -1*vec.y;
}
else
in >> vec.y >> y;
in >> charecter;
if(charecter == '-')
{
in >> vec.z >> z;
vec.z = -1*vec.z;
}
else
in >> vec.z >> z;
return in;
}
答案 0 :(得分:1)
正如用户902384在评论中所述,您需要解析字符串以适当地分配矢量值。您的解析逻辑可以根据需要复杂化,但是我将这些内容放在一起可以帮助您入门:
float ParseValue(const std::string& str);
void ParseVectorString(const std::string& equation, Vector3D& vec)
{
vec.x = vec.y = vec.z = 0.0f;
if (equation.empty())
return;
const size_t I_POSITION = equation.find('i');
const size_t J_POSITION = equation.find('j');
const size_t K_POSITION = equation.find('k');
// Logic assumes order is i, j, k.
// You can make it smarter if needed.
unsigned startPosition = 0;
if (I_POSITION != std::string::npos)
{
unsigned length = I_POSITION - startPosition;
vec.x = ParseValue(equation.substr(startPosition, length));
startPosition = I_POSITION + 1;
}
if (J_POSITION != std::string::npos)
{
unsigned length = J_POSITION - startPosition;
vec.y = ParseValue(equation.substr(startPosition, length));
startPosition = J_POSITION + 1;
}
if (K_POSITION != std::string::npos)
{
unsigned length = K_POSITION - startPosition;
vec.z = ParseValue(equation.substr(startPosition, length));
startPosition = K_POSITION + 1;
}
}
// Parse the value from the vector variable.
float ParseValue(const std::string& str)
{
unsigned startPosition = 0;
bool isNegativeValue = false;
if (str[startPosition] == '-')
{
isNegativeValue = true;
startPosition = 1;
}
float value = atof(str.substr(startPosition, str.length()).c_str());
return isNegativeValue ? value*-1 : value;
}