0

I'm currently solving CS50 Pset 2 but Im facing a little difficulty. This is my code:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
bool only_digits(string s);
char rotate(char c, int n);

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


    if (argc != 2 || only_digits(argv[1]) == false)
    {printf("Usage: ./caesar key\n");
    return 1;}

    string plain_text = get_string("plaintext:  ");

    int key = atoi(argv[1]) %26;
    int len = strlen(plain_text);

    char cipher[len];
    for (int i = 0; i < len; i++)
    {
    char new = rotate(plain_text[i], key);
    cipher[i] = new;

}
printf("Ciphertext: %s", cipher);
}
// checking every character of argv[1] is a digit
bool only_digits(string s)
{
    int len = strlen(s);
    for (int i = 0; i < len; i ++ )
        {if (!isdigit(s[i]))
        {
            return false;
        }
        }
    return true;
}

//rotate charc
char rotate(char c, int n)
{
char output;
if (c!= '\0')
{
int buffer = (int)c + n;
if (c >= 'a' && c <= 'z')
{
    if (buffer>122)
    {
        buffer = 97 + (buffer - 122) - 1;
        output = (char) buffer;
        return output;
    }
    else
    {return (char) buffer;}
}
else if (c >= 'A' && c <= 'Z')
{
    if (buffer > 90) {
        buffer = (65 + (buffer - 90) - 1);
        output = (char) buffer;
        return output;
    }
    else
    {return (char) buffer;}
}
else
{
    return c;
}

}
return c;

}

If I were to do ./caesar 4, with plaintext being "HELLO WORLD!", I'll get back LIPPS ASVPH!V Why do I have that additional 'V' character? Any help is appreciated! Still currently new to C language so I have no idea what's going on here

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Maverick
  • 11
  • 2

0 Answers0