0

My question is about a cs50 PSET. The goal is to create some sort of encryption program. From command line arguments there is a key inputted and every key letter should be replaced with the alphabet letter. As an example:

$ ./substitution YTNSHKVEFXRBAUQZCLWDMIPGJO

plaintext:  HELLO

ciphertext: EHBBQ 

My code is not totally okay for the concept yet but this question is only for the replacement of the letter part. Logic is broken and does not work as I should expect. Some help would be good. Thank you all for your time.

#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(int argc,string argv[]){
int i,p;
                 //JTREKYAVOGDXPSNCUIZLFBMWHQ
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string plaintext = get_string("plaintext: ");
for(i=0,p=0;i<26;i++,p++)
{while (p<strlen(plaintext))
    {

        if ((int)plaintext[p] == (int)alphabet[i])
        {plaintext[p] = (int)argv[1][i];}
    }

}
printf("%s\n",plaintext);
}
2
  • You have described two different problems - the seg fault and the coding logic. We try to deal with only one major issue per question. So, first things first. The seg fault needs to be resolved. It's critical that you have the skill to identify which line is causing the seg fault. Please read the following post and try to identify the offending line of code. Then we can go on from there. ;-) cs50.stackexchange.com/q/37065/4847 – Cliff B May 2 '20 at 18:32
  • I find it out incrementation on i was doubled and it refered to an array out of boundaries ı guess but still I think my statement should work fine but it does not :/ I am waiting for your help :) @CliffB – IDK May 2 '20 at 19:41
0

This is an infinite loop:

for(i=0,p=0;i<26;i++,p++)
{while (p<strlen(plaintext))
    {

        if ((int)plaintext[p] == (int)alphabet[i])
        {plaintext[p] = (int)argv[1][i];}
    }

}

The while loop must complete before the code returns to the for loop statement to increment p. But the while loop will never end because p is never changed inside of the while loop.

This should not have been a while loop. Instead, it should be two nested for loops. I'll leave it for you to figure out how to implement it.

There may or may not be other issues, but one problem/one question. ;=)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .