Understanding of code.

string choice;
string str;
cout<<"Do you want to encrypt or decrypt the message: ";
cin>>choice;
if(choice == "encrypt")
{
cout<<"Enter the string to encrypt:";
getline(cin, str); // get cin value and store them on the string.
getline(cin, str);
string ans = "";

/* int i;
for( i = 0 ; i < str.length() ; i++ )
ans += ascii_to_bin(str[i]) + " ";
cout<<ans<<endl<<endl; */

I copied this code from a friend, it is to convert ascii number to binary. But do not seem to understand the code from int i onwards. Please advice

For the second part it is to convert binary to ascii and i do not understand this part of his code. Please advice

int i = 0, j = 0;
while( i < str.length() )
{
j = i;
string temp = "";
while(j < str.length() && str[j] != ' ')
temp += str[j++];
i = j + 1;
cout<<bin_to_ascii(temp);
}
Last edited on
1
2
3
4
5
6
7
8
int i;
// spin through each character convert to number and add a  space
// eg; "ABC" becomes "65 66 67"
for( i = 0 ; i < str.length() ; i++ )
   ans += ascii_to_bin(str[i]) + " ";

// print the answer
cout<<ans<<endl<<endl;



the second part is a bit messy and handing it in would really show that it was copied from another student. theres no way 2 students in the same class would come up with this loop.

its trying to do the reverse of the first part.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
int i = 0, j = 0;                           // i is the master index that will run from 0 to length(), 
                                            // j is a working index just for each number in the string
while( i < str.length() )
{
   j = i;                                   // set this numbers starting index
   string temp = "";                        // prepare to receive new number
   while(j < str.length() && str[j] != ' ') // keep going til the end of string ot a space is encountered
      temp += str[j++];                     // append this digit to the new string

   i = j + 1;                               // update the master index to be just after where we just finished, 
                                            // ready for next time
   cout<<bin_to_ascii(temp);                // output this number
}

so, taking str="65 66 67", the inner loop will scan from index i to the end of string or a space, whichever comes first, copying characters to temp, first time round it should stop with "65" it will then print "A", it should then continue and find the other two numbers and convert those also, resulting in "ABC" being displayed one character at a time.

Get it running in a debugger, there are plenty of high quality free ones out there, even an online one at https://ideone.com/
Once its running you should single step the program and watch the data change after each step, then it will be much clearer.

[/code]
Last edited on
Registered users can post here. Sign in or register to post.