#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <ctime>
#include <iomanip>
using namespace std;
int randchar(void)
{//rand char generation
int c = ' ';
while (!isalpha(c))
{
c = rand() * 1010110;
c %= 26;
c += 'a';
c %= 'z';
}
return c;
}//end randchar
int main(int argc, char * argv[], char **env)
{//array input and processing
char c;
string s;
c = cin.get();
while (!cin.eof())
{//run until end of message
if(isalpha(c))
s = s + c;
c = cin.get();
//cout <<"s is: " << s.length() <<"\n";
int length = s.length(), side=1, count=0, row, col;
while((side * side) < length) //start matrix as one by one increase until string length = width/length of array sides
side++;
char matrix[side][side];//create char matrix [side][side]
for(row=0; row < side; row++) //increase rows until same size as side
{
for (col=0; col < side; col++)//increase cols until same size as side
{
if (count < length)//if count is less than string length
{
matrix[row][col] = s[count++];//fill matrix[row][column] using string s until count = string length
}
else
{
matrix[row][col] = randchar(); //if count >= string length, fill remaining space with rand characters
count++;
}//else end
}//for ends
}//for ends
for (col=0; col < side; col++)
{
for (row=0; row < side; row++)
cout << matrix[row][col]; //prints out final encrypted array
}//for ends
}//while end
}//end main
所以我在确定为什么这个代码打印出从1 x 1到s.length()x s.length()的每个数组而不是仅打印最终加密数组时遇到问题。 abcdefghi应打印出adgbehcfi,但它打印aaIboacbgacbdadIbeWcSMadMbeecfkadgbemcfQadgbehcfc adgbehcfi ,按Enter键后, adgbehcfi 。
我想我需要在while循环结束后打印出数组,或者我在这里错过了其他的东西?任何帮助将不胜感激。
答案 0 :(得分:0)
你做了一个嵌套的for循环,循环所有行和matrix
数组的所有列,并将print语句cout << matrix[row][col];
放在这个嵌套循环中。因此它将针对每行和每列执行。要解决此问题,您可以删除for循环,替换为:
for (col=0; col < side; col++)
{
for (row=0; row < side; row++)
cout << matrix[row][col]; //prints out final encrypted array
}//for ends
由此:
cout << matrix[side-1][side-1]; //prints out final encrypted array