How to concatenate strings in c++?

痞子三分冷 提交于 2019-12-01 01:12:44

If you want to use the streaming operators then use a std::stringstream, like this:-

string degreesToDMS(double angle)
{
  int intpart = 0;
  int intpart2 = 0;
  int intpart3 = 0;
  stringstream ss;
  ss << floor(angle) << "\xb0" << modf(angle, &intpart)*60 << "'" << modf(modf(angle, &intpart2), &intpart3)*60 << "\"";
  return ss.str ();
}

You need to first build the result in an std::ostringstream and then retrieve the string from it.

std::ostringstream ss;
ss << floor(angle) << "\xb0" << modf(angle, &intpart)*60 ...
return ss.str();

There are other ways of achieving this result; for instance, with C++11 you can use std::to_string to convert the values to std::string and then concatenate them together.

return std::to_string(floor(angle)) + "\xb0" + 
         std::to_string(modf(angle, &intpart)*60) + ...
std::string result;
result += std::to_string(floor(angle);
result += "\xb0";
result += std::to_string(modf(angle, &intpart) * 60);
return result;

Note that this requires C++11 to get std::to_string.

To concatenate a string in C++ all you need to do is use the + operator on two strings.

If you want to convert a int to a string use the stringstream

#include <string>
#include <sstream>
using namespace std;

int main()
{
    string firstString = "1st, ";
    string secondString = "2nd ";

    string lastString  = firstString + secondString;

    int myNumber = 3;

    std::stringstream converANumber;
    converANumber << myNumber;

    lastString = lastString + converANumber.str();

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!