C++循环输入string数组
时间: 2023-08-29 19:04:27 浏览: 162
你可以使用 `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数组赋值
您好!要将一个字符串数组赋值给另一个字符串数组,您可以使用循环遍历并逐个赋值。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string arr1[] = {"Hello", "World", "!"};
std::string arr2[3];
for (int i = 0; i < 3; i++) {
arr2[i] = arr1[i];
}
// 打印 arr2 中的字符串
for (int i = 0; i < 3; i++) {
std::cout << arr2[i] << " ";
}
return 0;
}
```
上述代码会将 `arr1` 中的字符串逐个复制到 `arr2` 中,并输出 `arr2` 中的字符串。运行结果为:`Hello World !`。
希望这可以帮到您!如有任何其他问题,请随时提问。
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;
}
```
这些方法都是常用的输入整型数组的方式,根据具体的需求选择适合的方法即可。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)