c++打印以下图案: * * * * * * * * * * * * * * * * * * * * * * * * * (1)用字符数组方法;(2)用string方法。
时间: 2024-05-12 09:11:23 浏览: 23
当然可以,以下是用字符数组方法和string方法打印上述图案的C++代码:
**方法一:字符数组**
```cpp
#include <iostream>
using namespace std;
int main() {
// 定义字符数组并初始化
char arr = {'*', '*', '*', '*', ' ',
'*', '*', '*', '*', ' ',
'*', '*', '*', '*', ' ',
'*', '*', '*', '*', ' ',
'*', '*', '*', '*', ''};
// 打印图案
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
cout << arr[i][j];
}
cout << endl;
}
return 0;
}
```
**方法二:string**
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
// 定义并初始化string对象
string str = "*" + string(4, ' ') + "*" + string(5, '*') + " ";
for(int i = 0; i < str.size(); i+=5) {
cout << str.substr(i, 5);
cout << endl;
}
return 0;
}
```
这两种方法都是使用二维数组或字符串来模拟图案,第一种方法使用了字符数组,第二种方法使用了string对象。它们都遵循图案的逻辑,从上到下,从左到右打印每个字符或字符串。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)