I'm creating a block cypher.
It works like this: you figure out how big a square two-dimensional array you need to hold the text, then you create and fill the block with text writing from left to right/top to bottom, then you print it out from top to bottom/left to right.
Anyways, by doing some testing by commenting out areas, I've determined that the program encounters the error starting at the for loop where it's supposed to write the string to the array.
CODE:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <ctype.h>
#include <cstring>
#include <cmath>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string buffer = "";
string buff2;
while (getline(cin, buff2))
{
buffer.append(buff2);
}
for (int i = buffer.length()-1 ; i >=0 ; i--)
{
if ( !isalnum ( buffer[i] ) )
{
buffer.erase( i,1 );
}
}
cout << buffer;
int static length = buffer.length();
int squareNum = static_cast <int> ( ceil(sqrt( static_cast <double> ( length ))));
char** block;
block = new char*[squareNum];
for(int i = 0; i < squareNum; i++)
block[i] = new char[squareNum];
int count = 0 ;
//encounters error here
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
block[j][i] = buffer[count++];
}
}
for (int i = 0 ; i < squareNum ; i++)
{
for (int j = 0 ; j < squareNum ; j++)
{
cout.put(block[i][j]);
}
}
for (int i = 0 ; i < squareNum ; ++i )
delete [] block[i] ;
delete [] block;
}
It compiles and everything but when I try running it through command prompt that's when I encounter the problem. I'm trying to read a .txt file. I can't figure out why it's encountering this error. Can anyone shed some light on this problem?
bufferover a range0toceil(sqrt(buffer.length()))^2which can be greater than max valid indexbuffer.length()-1.