#include<iostream> #include<conio.h> #include<math.h> #include<vector> #include<iterator> #include<string> using namespace std; int main() { int k=0; string s; cout<<"string "; getline(cin,s); //taking in a string from the user float n=s.size(); //storing size of string int f=floor((sqrt(n))); //floor of square root of input string int c=ceil((sqrt(n))); //ceiling int m=f*c; //storing product of f and c vector< vector<string> > vec(n<=m?f:++f, vector<string>(c)); //makes a 2d vector //depending on user's //string length for(int i=0;n<=m?i<f:i<++f;i++) //looping acc to user's input and assigning { for(int j=0;j<c;j++) //string to a matrix { if(k<s.size()) { vec[i][j]=s[k]; k++; } } } for(int j=0;j<c;j++) //printing the vector { { for(int i=0;n<=m?i<f:i<++f;i++) cout<<vec[i][j]; }cout<<" "; } getch(); } It's not working for n>m as for a string of length 8 characters it makes a vector of 2*3 thus failing to enclose the whole string in the matrix and which is why I am using ternary so as to make a vector of bigger size when it encounters cases like these. .So what am I doing wrong?
I'll just write the whole question.
One classic method for composing secret messages is called a square code. The spaces are removed from the english text and the characters are written into a square (or rectangle). The width and height of the rectangle have the constraint, floor(sqrt(word)) <= width, height <= ceil(sqrt(word)) The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as: imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau Sample Input: chillout Sample Output: clu hlt io
vector< vector<string> > vec(n<=m?f:++f, vector<string>(c));is just wrong, without having to even read it. Use of the comma operator in a ternary expression, one clause of the expression having typeint, the other having typestd::vector<string>- it's just obviously and intuitively wrong. Write something simpler, more obvious, and more expressive of what you're trying to achieve, particularly if you're "new to programming".