0

Here is my code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
    if (argc != 2) //prompting user to provide two command line arguments
    {
        printf("Retry, please enter a valid command-line argument\n");
        return 1;
    }

    int key = atoi(argv[1]);

    if (key <= 0) //prompting user to provide the correct key
    {
        printf("Retry, please provide a positive non-zero number\n");
        return 2;
    }

    else //prompting user to provide plain text
    {
        printf("Plaintext: ");
        string text = get_string();

        //increment i by 1 for every letter of the plain text
        for (int i = 0, n = strlen(text); i < n; i++)
            if (isalpha(text[i]) ) 
            {
                if (islower(text[i]) )
                // for upper case letters
                    {
                        printf("%c", (((text[i - 97] + key) % 26) + 97) );
                    }

                else if (isupper(text[i]) )
                // for lower case letters
                    {
                        printf("%c", (((text[i - 65] + key) % 26) + 65) );
                    }
            }

            else
            {
                printf("%c", text[i]);
            }
    }
    return 0;
    printf("\n");
}
1

In your code, the segmentation error is coming from your formula within printf. Take a look at text[i-65]. Instead of subtracting 65 from the value, it subtracts 65 places within the array causing the program to go out of bounds. i.e. For the first character, you would be looking for text[-65]. This is why your program is giving a segmentation error.

0

When you wrote text[i - 97], you probably meant text[i] - 97 (same for 65)

You must log in to answer this question.

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