【发布时间】:2014-05-05 10:44:16
【问题描述】:
这个程序的工作原理是让用户输入文本,使用 ctrl-z 结束程序,然后程序将字符串放入一个正方形 2D 数组中,然后从左到右从上到下显示,然后再到顶部从左到右。不幸的是,它变成了矩形而不是正方形。
这是我的代码:
#include <iostream>
#include <string>
using namespace std ;
int main (int argc, char *argv[], char **env)
{
string s ; s.clear() ;
int c = cin.get() ;
while (!cin.eof())
{
s += c ;
c = cin.get() ;
}
for ( int i = 0 ; i < s.length() ; ++i)
{
if (!isalpha(s[i]))
{
s.erase(i,1) ; // removes non-alphanumeric characters
--i ;
}
}
int side = 1 ;
while (side * side < s.length() )
{
++side ;
}
cout << endl << side << endl;
char block[side][side] ;
int i = 0;
for (int r=0; r<side; r++) //This loops on the rows.
{
for(int c=0; c<side; c++) //This loops on the columns
{
block[r][c] = s[i];
i++;
}
}
cout << endl;
for (int r=0; r<side; r++) //This loops on the rows.
{
for(int c=0; c<side; c++) //This loops on the columns
{
cout << block[r][c];
}
cout << endl ;
}
cout << endl ;
for (int c=0; c<side; c++) //This loops on the columns.
{
for(int r=0; r<side; r++) //This loops on the rows.
{
cout << block[r][c];
}
cout << endl;
}
cout << endl;
cout << s << endl ;
}
示例输入和输出:这是用于加密的示例文本
变成:Thisisasampletextforencryption
Thisis
asampl
etextf
orencr
yption
Taeoy
hstrp
iaeet
smxni
iptco
slfrn
它们应该是 6x6。相反,它们是 6x5 和 5x6。
【问题讨论】:
-
请考虑字母本身不是正方形,而是矩形。
-
最后一个循环交换循环变量但不交换索引。这不应该影响维度,但会影响值的输出顺序。
-
交换是正确的,但尺寸不正确。示例:这是一个用于加密的示例文本:Thisisasampletextforencryption Thisis asampl etextf orencr yption Taeoy hstrp iaeet smxni iptco slfrn 它们应该是 6x6。相反,它们是 6x5 和 5x6。编辑:哇,这些 cmets 的格式都关闭了。
-
thisisasampletextforencryption 只有 30 个字符长。您如何预计这会占用 36 个字符 (6x6)?
标签: c++ arrays loops for-loop multidimensional-array