'Why doesn't my function iterate through every character?
I am making a Caesar function for cs50(I'm new, so it's probably not the most efficient way to code it) and my function that encrypts my plaintext doesn't iterate through all the letters in the plaintext and only works with the first one. (I think there's something wrong with my rotate() function).
Here's my code:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
bool only_digits(string argv[]);
int rotate(string plaintext, int key);
int main(int argc, string argv[])
{
if(!(argc == 2 && only_digits(argv)))
{
printf("Usage: ./caesar key\n");
return 1;
}
int key = atoi(argv[1]);
string plaintext = get_string("plaintext: ");
char ciphered = (rotate(plaintext, key));
printf("ciphered: ");
for(int i = 0; i < strlen(plaintext); i++)
{
printf("%c", ciphered);
}
printf("\n");
}
bool only_digits(string argv[])
{
for(int i = 0; i < strlen(argv[1]); i++)
{
if(!isdigit(argv[1][i]))
{
return false;
}
}
return true;
}
int rotate(string plaintext, int key)
{
int cipher = 0;
for(int i = 0; i < strlen(plaintext); i++)
{
if (plaintext[i] == 'Z' || plaintext[i] == 'z')
{
cipher = plaintext[i] - 26 + key;
return cipher;
}
else if (isalpha(plaintext[i]))
{
cipher = plaintext[i] + key;
return cipher;
}
}
return 0;
}
Here's a screenshot of the terminal: enter image description here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
