search

Home  >  Q&A  >  body text

c++ - How to convert vector coordinates to string in the format of "(x=, y=)"

Code:
string str(double dX, double dY)//Convert vector coordinates to string, the format is "(x=, y=)"

{
    return "(x=" + dX + ", y=" + dY + ")";
}

Error message:
Expression must contain an integer or an unscoped enumeration type

过去多啦不再A梦过去多啦不再A梦2773 days ago1313

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-06-05 11:13:01

    Two common solutions.

    std::string v1(double dX, double dY) {
      std::ostringstream stream;
      stream << "(x=" << dX << ", y=" << dY << ")";
      return stream.str();
    }
    
    std::string v2(double dX, double dY) {
      char buff[1024];
      sprintf(buff, "(x=%f, y=%f)", dX, dY);
      return buff;
    }

    v2 may overflow.

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-05 11:13:01

    include<string>

    c++11 provides std::to_string for string conversion

    Or as mentioned above

    std::string v1(double dX, double dY) {
      std::ostringstream stream;
      stream << "(x=" << dX << ", y=" << dY << ")";
      return stream.str();
    }
    

    According to the original poster’s procedure, to_string conversion is more efficient.

    It is recommended to return const string

    reply
    0
  • Cancelreply