2017-04-20 48 views
0
#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并按下回车后,adgbehcfi凯撒移位问题

我在想,我需要在while循环结束后打印出数组还是我在这里丢失了别的东西?任何帮助将不胜感激。

+0

你有你的加密循环内打印循环。一些正确的缩进将很容易地显示出来。 – NathanOliver

回答

0

您做了一个嵌套for循环,循环所有行和matrix数组的所有列,并将打印语句cout << matrix[row][col];置于此嵌套循环中。所以它会针对每一行和每一列执行。本

for (col=0; col < side; col++) 
{ 
    for (row=0; row < side; row++) 
     cout << matrix[row][col]; //prints out final encrypted array 
}//for ends 

:为了解决这个问题,你可以删除的for循环,更换此

cout << matrix[side-1][side-1]; //prints out final encrypted array