c++ 字符串定义数组
时间: 2023-11-27 10:46:57 浏览: 49
在C++中,可以使用字符串数组来定义和存储多个字符串。字符串数组是一个字符指针数组,每个元素都指向一个字符串。以下是一个示例代码,展示如何定义和初始化一个字符串数组:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string strArray[3] = {"li", "zhang", "wang"};
for (int i = 0; i < 3; i++) {
cout << strArray[i] << endl;
}
return 0;
}
```
在上面的代码中,我们使用了string类型来定义字符串数组,并初始化了一个包含3个字符串元素的数组。然后,我们使用for循环遍历数组,并输出每个字符串元素的值。
相关问题
c++定义字符串数组
在C++中,可以使用以下语法定义字符串数组:
```c++
char str_array[10][20]; // 定义一个包含10个字符串,每个字符串最多包含19个字符的字符数组
```
其中,`str_array`是数组名,`10`表示数组中包含10个字符串,`20`表示每个字符串最多包含19个字符(因为还需要一个字符来存储字符串结尾的空字符`\0`)。
c++ 字符串数组定义
C++中定义字符串数组有多种方式,以下是两种常见的方法:
方法一:使用字符串字面值初始化数组
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string array[3] = {"li", "zhang", "wang"};
for (int i = 0; i < 3; i++) {
cout << array[i] << endl;
}
return 0;
}
```
方法二:使用循环逐个赋值
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string array[3];
array[0] = "li";
array[1] = "zhang";
array[2] = "wang";
for (int i = 0; i < 3; i++) {
cout << array[i] << endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)