(语言:C ++) 我有这个数组:
string myArray[] = {"Apple", "Ball", "Cat"};
是否可以将上述数组中的每个元素存储到新数组中?这样的事情。
char word1[] = myArray[0];
char word2[] = myArray[1];
char word3[] = myArray[2];
我检查了上面的代码,它会抛出一个错误。我如何获得此功能?我不能使用二维数组,因为我不知道我的实际程序中单词的长度。一个文件有单词列表,我必须将它读入数组并获取上面的字符串数组。
答案 0 :(得分:1)
根据您发布的示例,您正在寻找:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
string myArray[] = {"Apple", "Ball", "Cat"};
char test0[myArray[0].length()];
strcpy(test0, myArray[0].c_str());
char test1[myArray[1].length()];
strcpy(test1, myArray[1].c_str());
char test2[myArray[2].length()];
strcpy(test2, myArray[2].c_str());
int i=0;
for(i=0; i<(sizeof(test0)/sizeof(*test0)); i++)
cout<<test0[i]<<" ";
cout<<"\n";
for(i=0; i<(sizeof(test1)/sizeof(*test1)); i++)
cout<<test1[i]<<" ";
cout<<"\n";
for(i=0; i<(sizeof(test2)/sizeof(*test2)); i++)
cout<<test2[i]<<" ";
cout<<"\n";
return 0;
}
在上面的代码中,我创建了长度等于test0[]
中相应字符串的字符数组test1[]
,test2[]
和myArray[]
。然后我使用strcpy()
将相应的字符串从myArray[]
复制到字符数组(test0[]
等)。最后,我刚刚打印了这些新的字符数组。
工作代码here。
注意:我假设您使用的是GCC,因为它支持VLAs。如果没有,那么你可以使用特定长度的数组(或者更好,vector
)。
希望这有用。
答案 1 :(得分:0)
旧式(c ++ 98 / c ++ 03):
#include <string>
#include <iostream>
int main()
{
std::string myArray[] = { "Apple", "Ball", "Cat" };
char *firstString = new char[myArray[0].length() + 1];
char *secondString = new char[myArray[1].length() + 1];
char *thirdString = new char[myArray[2].length() + 1];
strcpy(firstString, myArray[0].c_str());
strcpy(secondString, myArray[1].c_str());
strcpy(thirdString, myArray[2].c_str());
std::cout << "firstString = " << firstString << std::endl;
std::cout << "secondString = " << secondString << std::endl;
std::cout << "thirdString = " << thirdString << std::endl;
delete firstString;
delete secondString;
delete thirdString;
return 0;
}
新风格(c ++ 11/14):
#include <string>
#include <iostream>
#include <memory>
int main()
{
std::string myArray[] = { "Apple", "Ball", "Cat" };
std::unique_ptr<char> firstString{ new char[myArray[0].length() + 1] };
std::unique_ptr<char> secondString{ new char[myArray[1].length() + 1]};
std::unique_ptr<char> thirdString{ new char[myArray[2].length() + 1]};
strcpy(firstString.get(), myArray[0].c_str());
strcpy(secondString.get(), myArray[1].c_str());
strcpy(thirdString.get(), myArray[2].c_str());
std::cout << "firstString = " << firstString.get() << std::endl;
std::cout << "secondString = " << secondString.get() << std::endl;
std::cout << "thirdString = " << thirdString.get() << std::endl;
return 0;
}