convert program
Can anyone teach me how to convert my code using class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main(){
string s;
cin>>s;
int len = s.length();
int width,height,i,j,k;
width=floor(sqrt(len)); //rows
height=ceil(sqrt(len)); //columns
for(i=0;i<height;i++)
{
for(j=0;j<height;j++)
{
k=(j*height)+i;
cout<<s[k];
}
cout<<"\n";
}
return 0;
}
|
I tried it, but I'm stuck.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class squareCipher{
private:
int width;
int height;
public:
int len;
void set_Width()
};
int main(){
squareCipher simmon;
string input;
cout << "Please Input a String: ";
cin >> input;
simmon.len = input.length();
system("Pause");
return 0;
}
|
Last edited on
Perhaps like so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include<iostream>
#include<string>
#include<cmath> //!! not math.h
using namespace std;
class squareCipher{
private:
int width;
int height;
string s;
public:
squareCipher(const string &s_) {
s = s_;
int len = s.length();
width=floor(sqrt(len)); //rows
height=ceil(sqrt(len)); //columns
}
void print() {
for(int i=0;i<height;i++) {
for(int j=0;j<height;j++) {
int k=(j*height)+i;
cout<<s[k];
}
cout<<"\n";
}
}
};
int main() {
squareCipher bob("hello");
bob.print();
}
|
Watch out for out of bound accesses on your string indexing when you print.
Thank you @salem c. Big help to someone like me who is new. :) I'll learned from it a lot.
Shouldn't the inner loop increment up to width
?
Topic archived. No new replies allowed.