如何格式化重载的 C++ 输入运算符?

How do I format an overloaded c++ input operator?

我正在尝试创建一个可以用作矢量的矢量对象。但是,我在输入时遇到问题。我想格式化输入,以便我可以键入 3.4i+5.4j-8.4k,它会将相应的值放入 class.

中的正确变量中

Class:

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

正如 user902384 在评论中所述,您需要解析字符串以适当地分配向量值。根据要求,您的解析逻辑可能会很复杂,但我将以下内容放在一起可能会帮助您入门:

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