首先创建一个二维数组,
然后将输入的字符串按从左到右的顺序依次从二维数组的倒数第一列开始装入,装满装第二列,以此类推....
#include <iostream> #include <cstring> using namespace std; const int N = 1010; char g[N][N]; int n; int main() { int r, c, k = 0; cin >> n; string s; getchar(); getline(cin, s); int leng = s.size(); r = n; if(leng % n == 0) c = leng / n; else c = leng / n + 1; for(int i = 0; i < n; i++) g[i][0] = ' '; for(int j = c - 1; j >= 0; j--) for(int i = 0; i < r; i++) { g[i][j] = s[k++]; if(k==leng) break; } for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) cout << g[i][j]; if(i != r - 1) cout << endl; } return 0; }