晶晶同学非常喜欢方形,她希望打印出来的字符串也是方形的。老师给了晶晶同学一个字符串"ACM",晶晶同学突发奇想,如果任意给定义一个整数n,能不能打印出由这个字符串组成的正方形字符串呢?要求是每行要使用n个给定的字符串。 请你编程实现一下。c++语言
时间: 2024-04-10 14:34:02 浏览: 15
当然可以!下面是一个使用C++语言实现的程序,可以根据输入的整数n打印出由给定字符串组成的正方形字符串:
```cpp
#include <iostream>
#include <string>
using namespace std;
void printSquareString(const string& str, int n) {
int len = str.length();
int squareSize = n * n;
if (len > squareSize) {
cout << "Error: The length of the string is larger than the square size." << endl;
return;
}
for (int i = 0; i < squareSize; i++) {
int pos = i % len;
cout << str[pos];
if ((i + 1) % n == 0) {
cout << endl;
}
}
}
int main() {
string str;
int n;
cout << "Enter the string: ";
cin >> str;
cout << "Enter the size of the square: ";
cin >> n;
cout << "Square string:" << endl;
printSquareString(str, n);
return 0;
}
```
在这个程序中,首先输入一个字符串和一个整数n。然后,程序会检查给定字符串的长度是否大于正方形的大小,如果是,会输出错误信息。接下来,程序会遍历正方形的每个位置,将字符串中对应位置的字符打印出来。每行打印n个字符后换行。
希望这个程序能够满足晶晶同学的需求!如果还有其他问题,请随时提问。