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
  • 44,644
  • 9
  • 83
  • 100
Ruthg
  • 241
  • 2
  • 4
  • 11

4 Answers4

20

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
  • 44,644
  • 9
  • 83
  • 100
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
  • 44,967
  • 21
  • 135
  • 183
0
std::ostringstream oss;
oss << major << "." << minor;

Receive the generated string via oss.str().

sstn
  • 3,050
  • 19
  • 32
0

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

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

std::cout << ss.str();
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176