Help! I’m trying to figure out this code our professor gave us –
#include <stdio.h>
#include <string.h>
void encrypt(int offset, char *str) {
int i,l;
l=strlen(str);
printf("\nUnencrypted str = \n%s\n", str);
for(i=0;i<l;i++)
if (str[i]!=32)
str[i] = str[i]+ offset;
printf("\nEncrypted str = \n%s \nlength = %d\n", str, l);
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
printf ("Please enter a line of text, max %d characters\n", sizeof(str));
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
We are suppose to do the following:
-
Convert the
Ccode toC++. -
Add codes to the “decrypt” method to decipher the encrypted text.
-
Change the code to use
pointeroperations instead ofarrayoperations to encrypt and decrypt messages. -
In the main method, call the “decrypt” method to decipher the encrypted text (str).
This is as far as I managed to go, but I’m pretty much stuck now. Especially since I have no background in the C language. Any help would be appreciated.
#include <iostream>
#include <string.h>
void encrypt(int offset, char *str)
{
std::cout << "\nUnencrypted str = \n" << str;
char *pointer = str;
while(*pointer)
{
if (*pointer !=32)
*pointer = *pointer + offset;
++pointer;
}
std::cout <<"\nEncrypted str =\n" << str << "\n\nlength = ";
}
void decrypt(int offset, char *str) {
// add your code here
}
void main(void) {
char str[1024];
std::cout << "Please enter a line of text max " << sizeof(str) << " characters\n";
if (fgets(str, sizeof(str), stdin) != NULL)
{
encrypt(5, str); // What is the value of str after calling "encrypt"?
// add your method call here:
}
}
The code you posted should work in C++ as well as C. There shouldn’t be a need to “convert” anything, unless there are specific requirements that you haven’t told us about.
Your array-to-pointer conversion looks correct, although I would argue that the code is more readable in the array form.
For your
decryptmethod, you will want to write code that does the inverse of what theencryptmethod does. The best way to approach this is to run some sample text throughencryptand examine what the output looks like. The function transforms the input a single character at a time, so you should be able to map input to output on a byte-by-byte basis. With this information, you can detect the pattern and construct a function that makes the transformation in the other direction.