Split a string and store into 2D vector

Hello guys, i am having trouble with parsing out string value into a 2D vector. Suppose i have the string "attack at dawn " consisting of 15 characters, i will like to store it into a 2D vector with 5 rows and 3 columns and the result is as follow.

Vector[0][0] = "a"
Vector[0][1] = "t"
Vector[0][2] = "t"
Vector[1][0] = "a"
Vector[1][1] = "c"
Vector[1][2] = "k"
Vector[2][0] = " "
Vector[2][1] = "a"
Vector[2][2] = "t"
etc...


Here is a draft code that i did but is not working as desired. Hope you guys can help me out thanks..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<vector <string > > plaintextVector;  
vector<string> row;
string totalString = "attack at dawn ";
int dimension = 3;


    for (int i = 0; i < totalString.size()/dimension; i++) {

       
        for (int j = 0; j < totalString.size(); j++) {

            row.push_back(totalString.substr(j, 1));

        }

        plaintextVector.push_back(row);

    }
Last edited on
For yours, you need to reset the row each time otherwise you'll be appending more and more and more to the end of each row.

In any case, why are you doing it with strings? Why not just use a vector of chars? It makes more sense, logically, and rather than using substr you can just use the element access operator ([]).
Topic archived. No new replies allowed.