阅读量:92
在C++中,可以使用以下方法来给字符串数组赋值:
- 使用下标赋值:直接通过下标索引来赋值字符串数组的每个元素。
#include
#include
int main() {
std::string arr[3];
arr[0] = "Hello";
arr[1] = "World";
arr[2] = "C++";
for (int i = 0; i < 3; i++) {
std::cout << arr class="hljs-keyword">return 0;
}
- 使用strcpy函数:利用strcpy函数将字符串赋值给数组中的元素。
#include
#include
int main() {
char arr[3][10];
strcpy(arr[0], "Hello");
strcpy(arr[1], "World");
strcpy(arr[2], "C++");
for (int i = 0; i < 3; i++) {
std::cout << arr class="hljs-keyword">return 0;
}
- 使用std::vector:使用std::vector来管理字符串数组。
#include
#include
#include
int main() {
std::vector arr;
arr.push_back("Hello");
arr.push_back("World");
arr.push_back("C++");
for (int i = 0; i < arr class="hljs-built_in">size(); i++) {
std::cout << arr class="hljs-keyword">return 0;
}
以上是几种常见的给字符串数组赋值的方法,选择适合自己需求的方法来操作字符串数组。