Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from unsigned short to string c++ [duplicate]

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

like image 701
Ruthg Avatar asked Feb 14 '13 09:02

Ruthg


2 Answers

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);
like image 138
billz Avatar answered Nov 16 '22 07:11

billz


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

std::string version = std::to_string(major)
              + "." + std::to_string(minor);
like image 3
leemes Avatar answered Nov 16 '22 08:11

leemes