我想在 std::vector<unsigned char>
中显示数字在屏幕上,但在发送给收件人的途中,我需要将这些数字填充到 std::string
中.
无论我尝试什么( atoi
、 reinterpret_cast
、 string.c_str()
...),要么是胡说八道,要么是这些原始数字的字母表示 - 即它们对应的 ascii 字符。
那么我如何轻松(最好是标准方法)转换 vector<unsigned char> {1,2,3}
进入 string "1-2-3"
?
在我提到的原始帖子(后来编辑)中,我可以用 C# 或 Java 来做到这一点。 应 πìντα ῥεῖ 的要求提供 C# 或 Java 示例,这里是一个快速的 Linq C# 方式:
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::vector<unsigned char> v {1, 2, 3};
std::string s; // result
auto sep = ""; // continuation separator
for(auto n: v)
{
s += sep + std::to_string(n);
sep = "-"; // change the continuation separator after first element
}
std::cout << s << '\n';
continuation separator 开始时为空,并在连接第一个输出后发生变化。
输出:
1-2-3
关于c# - 将 vector<unsigned char> {1,2,3} 转换为字符串 "1-2-3"AS DIGITS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137997/