test / HelloWorld

Create hello world
Artistic License 2.0
6 stars 34 forks source link

Code Caesar #38

Closed lacoste745 closed 2 months ago

lacoste745 commented 2 months ago

include

include

include

include

include

// Function prototypes bool only_digits(string s); char rotate(char c, int k);

int main(int argc, string argv[]) { // Check for valid number of arguments if (argc != 2) { printf("Usage: ./caesar key\n"); return 1; }

// Check if the key is valid (only digits)
if (!only_digits(argv[1]))
{
    printf("Usage: ./caesar key\n");
    return 1;
}

// Convert key from string to integer
int key = atoi(argv[1]);

// Prompt user for plaintext
string plaintext = get_string("plaintext:  ");

// Encrypt plaintext
printf("ciphertext: ");
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
    printf("%c", rotate(plaintext[i], key));
}
printf("\n");

return 0;

}

// Function to check if a string contains only digits bool only_digits(string s) { for (int i = 0, n = strlen(s); i < n; i++) { if (!isdigit(s[i])) { return false; } } return true; }

// Function to rotate a character by k positions char rotate(char c, int k) { if (isupper(c)) { return 'A' + (c - 'A' + k) % 26; } else if (islower(c)) { return 'a' + (c - 'a' + k) % 26; } else { return c; } }