从无符号短整型转换为字符串 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14871388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:46:02  来源:igfitidea点击:

Convert from unsigned short to string c++

c++type-conversion

提问by Ruthg

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

如何使用 C++ 从 unsigned short 转换为字符串?我有两个无符号的短变量:

    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

谢谢

回答by billz

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

可以使用std::stringstreamstd::to_string(C++11) 或 boost::lexical_cast

#include<sstream>

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

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

std::to_string:

std::to_string:

std::string s = std::to_string(major) + "." +std::to_string(minor);

回答by leemes

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

在 C++11 中,你不需要一些流来做这个:

std::string version = std::to_string(major)
              + "." + std::to_string(minor);

回答by sstn

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

Receive the generated string via oss.str().

通过 接收生成的字符串oss.str()

回答by Ivaylo Strandjev

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

使用std::ostringstream. 您需要包含 header <sstream>

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

std::cout << ss.str();