Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I made a simple encryption and decryption program in c and is not working as expected

// Write a encryption program which encrypts the string by adding 1 to its ASCII value.
#include <stdio.h>
#include <string.h>

void encrypt(char *str)
{
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr + 1; // This will add integer 1 to the value of character stored in ptr i.e. its ASCII value.
        *ptr++;
    }
}

void decrypt(char *str){
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr -1; // This will subtract 1 from the ASCII value and restore the original string.
        *ptr++;
    }
    
}
int main()
{
    char message[] = "We are what we choose to be!"; 
    encrypt(message);
    printf("The encrypted message is %s\n\n", message);

    char pwd[20] = "omkaushik";
    char input[20];
    printf("Enter password to decrypt the message\n");
    gets(input);

    int result = strcmp(pwd, input);
   while (result != 0)
   {
     printf("The password entered is wrong\n");
     printf("Enter the password again\n");
     gets(input);
     int result = strcmp(pwd, input);
   }
   decrypt(message);
        printf("The password entered is accepted....\n");
        printf("%s",message);

    return 0;
}

In this program when I enter the correct password at the start, it decrypts the message successfully but when I enter a wrong password and later try to enter the correct password, it doesn’t exit the loop.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First gets is deprecated and unsafe and should never be used.
Second, and this is your question, inside your loop you declare a local variable instead of updating the one in the outer scope

 int result = strcmp(pwd, input);

replace it with

 result = strcmp(pwd, input);

Will update the test inside the loop

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading