I'm looking for some (more) help trying to figure out caesar. I finally got it to compile but it's not working properly. When I run check50, it looks like there are two main issues -
one, it's not correctly checking if every character of the key is a digit (the sad face is on "handles non-numeric key - timed out while waiting for program to exit"). I've been wracking my brain over the only_digits
function and how to fix it but can't figure it out.
and the second thing is that while the program is correctly shifting each plaintext, it's not printing out the result.
Any help greatly appreciated!
original question: help with Caesar problem from Pset2
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool only_digits(string s);
char rotate(char c, int n);
int main(int argc, string argv[])
{
// make sure program is run with just one command line argument
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
// make sure every digit in argv[1] is a digit
only_digits(argv[1]);
// convert argv[1] from a 'string' to an 'int' and store that number in variable "key"
int key = atoi(argv[1]);
// prompt user for plaintext
string plaintext = get_string("plaintext: ");
// length of the plaintext
int text_length = strlen(plaintext);
// create string for ciphertext with the same length as the plaintext
char ciphertext[text_length];
// for each character in the plaintext
for (int i = 0, j = text_length; i < j; i++)
{
// rotate the character only if it's a letter
if (isalpha(plaintext[i]))
{
rotate(plaintext[i], key);
ciphertext[i] = plaintext[i];
}
else
{
ciphertext[i] = plaintext[i];
}
}
// print out the ciphertext
printf("ciphertext: %c\n", ciphertext[text_length]);
return 0;
}
bool only_digits(string s)
{
for (int i = 0, j = strlen(s); i < j; i++)
{
if isdigit(s[i])
{
return 0;
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
return 0;
}
char rotate(char c, int n)
{
char rotated_char;
if (isupper(c))
{
// rotate n number of places forward in the alphabet, uppercase, A = 65, lowercase, a = 97
rotated_char = ((c - 65) + n) % 26;
// return the result
c = rotated_char + 65;
}
else if (islower(c))
{
rotated_char = ((c - 97) + n) % 26;
c = rotated_char + 97;
}
else
{
rotated_char = c;
}
return rotated_char;
}