C++ 初始化一个字符数组
时间: 2023-11-14 12:14:51 浏览: 35
在C语言中,可以使用以下方式初始化一个字符数组:
1. 使用字符串字面值初始化
```c
char str[] = "Hello World";
```
2. 逐个赋值初始化
```c
char str[12];
str[0] = 'H';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = ' ';
str[6] = 'W';
str[7] = 'o';
str[8] = 'r';
str[9] = 'l';
str[10] = 'd';
str[11] = '\0'; // 添加字符串结尾的空字符
```
3. 使用数组初始化
```c
char str[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
```
无论使用哪种方式,都需要注意字符数组的大小必须足够存储所初始化的字符串,包括结尾的空字符。
相关问题
c++如何初始化多个字符串数组
你可以通过以下两种方式初始化多个字符串数组:
1. 逐个初始化
```cpp
#include <iostream>
#include <string>
int main() {
std::string str_arr1[3] = {"hello", "world", "!"};
std::string str_arr2[4] = {"how", "are", "you", "?"};
// 输出两个字符串数组的内容
for (int i = 0; i < 3; i++) {
std::cout << str_arr1[i] << " ";
}
std::cout << std::endl;
for (int i = 0; i < 4; i++) {
std::cout << str_arr2[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
2. 使用二维数组初始化
```cpp
#include <iostream>
#include <string>
int main() {
std::string str_arr[2][3] = {{"hello", "world", "!"}, {"how", "are", "you"}};
// 输出两个字符串数组的内容
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
std::cout << str_arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
```
以上两种方式都可以初始化多个字符串数组,选择哪种方式取决于你的具体需求。
用c++输入流初始化一个字符串数组
可以使用C++中的`std::getline()`函数从输入流中读取一行字符串,然后使用`std::stringstream`将该字符串分割成一个字符串数组。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string input;
cout << "请输入一行字符串: ";
getline(cin, input); // 从标准输入流中读取一行字符串
istringstream iss(input); // 使用输入字符串初始化 stringstream 对象
string str;
string stringArray[100]; // 假设最多有100个字符串
int index = 0;
while (iss >> str) { // 从 stringstream 中读取每个字符串
stringArray[index++] = str;
}
cout << "分割后的字符串数组为: " << endl;
for (int i = 0; i < index; i++) {
cout << stringArray[i] << endl;
}
return 0;
}
```
在上面的代码中,我们使用`std::getline()`函数从标准输入流中读取一行字符串,并使用该字符串初始化一个`std::stringstream`对象。然后,我们使用`>>`运算符从`std::stringstream`对象中依次读取每个字符串,并将它们存储在一个字符串数组中。最后,我们遍历字符串数组并打印每个字符串。