简体   繁体   中英

C++ creating a two-dimensional array based on user input string length

I have an assignment to create a block transposition cipher program. A user is to input a phrase of their choice, and the program is to strip the phrase of spaces, punctuation, and make lowercase, before reading its length and creating a two-dimensional array the size of the nearest square that will fit all the chars in the mutated string, and filling in the remaining space with random letters.

Problem is, I'm having issues with creating that square.

I have this so far:

int main()
{
    string input;
    cout << "Please enter message to cipher." << endl;
    getline(cin, input);

    /* do punctuation removal/mutation */

    int strLength = input.length(); //after mutation

    /* need to find the square here before applying sizes and values to arrays */

    char * original = new char[][]; // sizes pending
    char * transposed = new char[][]; // sizes pending

    for (int i = 0; i <= /* size pending */ ; i++)
    {
        for (int j = 0; j <= /* size pending */ ; j++)
        {
            transposed[j][i] = original[i][j];
        }
    }

    /* do more stuff here */
}

any ideas?

(I already have done the mutation portion; tested with alternate code)

You can't do eg

char * original = new char[][];

First of all you are trying to create an array of arrays (or pointer of pointers) and assign it to a single pointer. You need to do it in two steps:

  1. Allocate the "outer" array:

     char **original = new char* [size];
  2. Allocate the "inner" strings:

     for (int i = 0; i < size; i++) original[i] = new char [other_size];

However I would highly recommend against using that! Instead you should be using std::vector instead of "arrays" allocated on the heap, and if the contents are strings then use std::string :

std::vector< std::vector< std::string > > original;

You can take the square root of the length, round down to an integer, and add one to get the new length.

int len = (int)(sqrt(strLength) + 1e-9) + 1;

You'd then malloc the square using len and fill as you normally would.

I believe you do not need the "new" to create your storage. Following code should just do the job:

char buf[size][size]; // size is a variable
... // populate your buf

char tmp;
for(int i = 0; i < size; i++) {
  for(int j = 0; j < i; j++) {
    tmp = buf[i][j];
    buf[i][j] = buf[j][i];
    buf[j][i] = tmp;
  }
}

This does the transpose in place. You don't need another array to store the char's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM