0

Hey all I asked a question related to this code earlier and got a lot of helpful answers (I'm very green at coding). While I overcame my initial problem and corrected a few more mistakes I've run into another error that I can't seem to fix. I keep getting the Segmentation fault but I want it to prompt the user to give a second argument. Along with that when I do give the number, the code doesn't seem to actually encrypt the text Any suggestions or blaring issues I missed?

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{

int num;
int k = atoi(argv[1]);
string output;

        if(argc != 2)
        {
                printf("K not included in command");
                return 1;
        }



        string s = get_string("Insert Lowercase Message:");

        for (int i = 0, n = strlen(s); i < n; i++)
        {
                char c = s[i];
                if (c >= 'A' && c <= 'Z')
                {
                        num = 'A';
                if (c >= 'a' && c <= 'z')
                        num = 'a';
                
                printf("%c", (c - num + k) % 26 + num);
                }
                else
                        printf("%c", c);
        }
        
        

}
Quise
  • 7
  • 1
  • You have `int k = atoi(argv[1]);` but you didn't check `argc` first to see if anything was entered before accessing `argv`. You do check it, but too late. The `int k = atoi(argv[1]);` must go *after* your check. – Weather Vane Jul 03 '21 at 18:29

1 Answers1

1

You have your braces misaligned where you are testing the case of the letters. The way it is written, if a lowercase case letter is encountered, the uppercase test will fail and you will drop through to the else case. What you want is something like this:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{

    int num;
    int k;
    string output;
    char c;

    if(argc != 2)
    {
        printf("K not included in command");
        return 1;
    }

    k = atoi(argv[1]);
    string s = get_string("Insert Lowercase Message:");

    for (int i = 0; c = s[i]; i++)
    {
        if (isalpha(c))
        {
            if (isupper(c))
                num = 'A';
            else   // islower
                num = 'a';
            printf("%c", (c - num + k) % 26 + num);
        }
        else
            printf("%c", c);
    }
}
SGeorgiades
  • 1,771
  • 1
  • 11
  • 11