How to concatenate strings in c++?

删除回忆录丶 提交于 2019-11-30 21:14:01

问题


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

This function takes in an angle in degrees and outputs a latitude.

I am getting errors on the return statement. How do I properly concatenate different data types to a string in C++?


回答1:


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



回答2:


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) + ...



回答3:


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.




回答4:


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();

}


来源:https://stackoverflow.com/questions/12712858/how-to-concatenate-strings-in-c

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