11

How can I convert from unsigned short to string using C++? I have tow unsigned short variables:

    unsigned short major = 8, minor = 1;

I want to join them for on string, looks like:

    std::string version = major + "." + minor;

how can I do it? will aprrechiate a small sample code.

Thanks

billz
  • 43,318
  • 8
  • 77
  • 98
Ruthg
  • 241
  • 2
  • 4
  • 11

4 Answers4

19

could use std::stringstream or std::to_string(C++11) or boost::lexical_cast

#include<sstream>

std::stringstream ss;
ss << major  << "." << minor;

std::string s = ss.str();

std::to_string:

std::string s = std::to_string(major) + "." +std::to_string(minor);
billz
  • 43,318
  • 8
  • 77
  • 98
3

In C++11, you don't need some stream do do this:

std::string version = std::to_string(major)
              + "." + std::to_string(minor);
leemes
  • 43,629
  • 21
  • 127
  • 181
0
std::ostringstream oss;
oss << major << "." << minor;

Receive the generated string via oss.str().

sstn
  • 3,024
  • 18
  • 30
0

Use std::ostringstream. You need to include the header <sstream>.

std::ostringstream ss;
ss << major << "." << minor;

std::cout << ss.str();
Ivaylo Strandjev
  • 66,530
  • 15
  • 117
  • 170