[英]Unpack char array to strings in c++
There must be a more elegant way to unpack a char array to array of strings: 必须有一种更优雅的方法来将char数组解压缩为字符串数组:
void loadNames(int size, char *inp[])
{
size_t i;
for (i = 0; i < size; i++){
string s = ""
while ( char(*inp[i]) != '\0' ) s.push_back(*inp[i]++);
cout << "String " << i << " = " << s.c_str() << endl;
}
}
Any clues - highly appreciated! 任何线索-高度赞赏!
There's a simple way to construct all those std::string
s and put them into a std::vector
(No extraneous copies): 有一种简单的方法来构造所有这些std::string
并将它们放入std::vector
(无多余副本):
std::vector<std::string> v(inp, inp+size);
This is the range-initializer of vector, combined with the c-string initializer of string. 这是向量的范围初始化程序,与string的c字符串初始化程序结合使用。
Use a std::vector<std::string>
and use its range constructor to fill it. 使用std::vector<std::string>
并使用其范围构造函数填充它。 Then just iterate through and print each string: 然后遍历并打印每个字符串:
void loadNames(int size, char* inp[])
{
std::vector<std::string> v(inp, inp + size);
size = 0;
for (auto&& x : v) {
std::cout << "String " << ++size << x << std::endl;
}
}
Directly construct from the char*
. 直接从char*
构造。
string s(inp[i]);
cout << "String " << i << " = " << s.c_str() << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.