转换vector< unsigned char> {1,2,3}转换为字符串“ 1-2-3”作为数字 [英] Convert vector<unsigned char> {1,2,3} into string "1-2-3" AS DIGITS
问题描述
我想在屏幕上的 std :: vector< unsigned char>
中显示数字,但是在到达接收者的途中,我需要将这些数字塞入 std :: string
。
I want to display numbers in a std::vector<unsigned char>
on a screen, but on its way to the recipient, I need to stuff these numbers into a std::string
.
无论我尝试了什么( atoi
, reinterpret_cast
, string.c_str()
...),给了我一个废话或一封信
Whatever I tried (atoi
, reinterpret_cast
, string.c_str()
...), gave me either a nonsense, or a letter representation of those original numbers - i.e. their corresponding ascii characters.
所以我如何轻松地(最好是标准方法)转换 vector< unsigned char> {1,2,3}
转换为字符串 1-2-3
?
So how do I easily (preferably standard method) convert vector<unsigned char> {1,2,3}
into a string "1-2-3"
?
我在原始帖子(后来编辑)中提到,我可以用C#或Java做到这一点。
根据πάνταῥεῖ的要求提供C#或Java示例,这是一种快速的Linq C#方式:
In the Original Post (later edited) I mentioned, that I could do that in C# or Java. Upon the request of πάντα ῥεῖ to provide example in C# or Java, here is a quick Linq C# way:
public static string GetStringFromListNumData<T>(List<T> lNumData)
{
// if (typeof(T) != typeof(IConvertible)) throw new ArgumentException("Expecting only types that implement IConvertible !");
string myString = "";
lNumData.ForEach(x => myString += x + "-");
return myString.TrimEnd('-');
}
推荐答案
只需使用 std :: ostringstream
:
std::vector<unsigned char> v{1,2,3};
std::ostringstream oss;
bool first = true;
for(auto x : v) {
if(!first) oss << '-';
else first = false;
oss << (unsigned int)x;
}
std::cout << oss.str() << std::endl;
这篇关于转换vector< unsigned char> {1,2,3}转换为字符串“ 1-2-3”作为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!