[英]Unpack char array to strings in c++
必須有一種更優雅的方法來將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;
}
}
任何線索-高度贊賞!
有一種簡單的方法來構造所有這些std::string
並將它們放入std::vector
(無多余副本):
std::vector<std::string> v(inp, inp+size);
這是向量的范圍初始化程序,與string的c字符串初始化程序結合使用。
使用std::vector<std::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;
}
}
直接從char*
構造。
string s(inp[i]);
cout << "String " << i << " = " << s.c_str() << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.