EDIT:
Here is the new "only_digits" function that I'm struggling with:
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;
}
}
}
I think I understand from the comment below that I'm not including the return = 0 in the right place, so it's returning to the main function potentially before it's finished checking all the characters, is that right? I can't seem to figure out what I need to put there (before the return = 0) in order to tell it to continue checking until the end of the array.
Looking for some help figuring out the error I'm getting for line 44:
It seems like I can't transfer the value of a single location within "plaintext[]" to the same location in "ciphertext[]"? I created the string "ciphertext" with the idea that that is where the information will be stored from each function rotating the characters (or not, as necessary) and then eventually to be printed out at the end. Any help TIA!
#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
string 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);
}
else
{
ciphertext[i] = plaintext[i];
}
}
// print out the ciphertext
printf("ciphertext: %s\n", ciphertext[text_length]);
}
bool only_digits(string s)
{
for (i = 0, j = strlen(s); i < j; i++)
{
if (isdigit((char)s[i]) == 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
}
}
char rotate(char c, int n)
{
char rotated_char;
if (isupper(plaintext[i]))
{
// rotate n number of places forward in the alphabet, uppercase
(((plaintext[i]) - 65) + key) % 26 = rotated_char;
// return the result
ciphertext[i] = rotated_char + plaintext[i];
}
else if (islower(plaintext[i]))
{
(((plaintext[i]) - 97) + key) % 26 = rotated_char;
ciphertext[i] = rotated_char + plaintext[i];
}
}