C++循环输入string数组
时间: 2023-08-29 19:04:27 浏览: 72
你可以使用 `for` 循环来输入 `string` 数组,具体操作如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
const int N = 5; // 数组大小
string strArr[N]; // 声明一个存储string类型的数组
// 循环输入
for(int i = 0; i < N; i++) {
cout << "请输入第" << i+1 << "个字符串:";
cin >> strArr[i];
}
// 输出数组中的元素
for(int i = 0; i < N; i++) {
cout << "第" << i+1 << "个字符串是:" << strArr[i] << endl;
}
return 0;
}
```
在上述代码中,我们首先声明了一个 `string` 类型的数组 `strArr`,其大小为 `N`。然后,使用 `for` 循环依次输入每个元素的值。最后,再使用 `for` 循环输出数组中的每个元素的值。
相关问题
c++两个string数组赋值
你可以使用C++中的赋值操作符(=)来将一个字符串数组的值赋给另一个字符串数组。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string arr1[] = {"Hello", "World"};
std::string arr2[2];
// 使用赋值操作符将arr1的值赋给arr2
arr2[0] = arr1[0];
arr2[1] = arr1[1];
// 打印arr2的值
for (const auto& str : arr2) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
```
在这个例子中,我们有两个字符串数组:`arr1`和`arr2`。首先,我们为`arr1`赋予初始值"Hello"和"World"。然后,我们使用赋值操作符将`arr1`的值逐个赋给`arr2`。最后,我们打印`arr2`的值,输出结果为"Hello World"。
请注意,这里的赋值操作只适用于字符串的赋值,如果你需要复制整个数组,可以使用`std::copy`函数或者循环遍历进行赋值。
C++怎么输入整型数组
在C++中,可以通过以下几种方式输入整型数组:
1. 使用循环结构和cin逐个读取数组元素:
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入整型数组的长度:";
cin >> n;
int arr[n];
cout << "请输入" << n << "个整数:";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "您输入的整型数组是:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
2. 使用循环结构和getline函数读取一行字符串,然后利用字符串流istringstream逐个解析出整数并存入数组:
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int n;
cout << "请输入整型数组的长度:";
cin >> n;
cin.ignore(); // 忽略上一个输入操作留下的换行符
string line;
cout << "请输入" << n << "个整数,用空格分隔:";
getline(cin, line);
istringstream iss(line);
int arr[n];
for (int i = 0; i < n; i++) {
iss >> arr[i];
}
cout << "您输入的整型数组是:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
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_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)
![](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)