#include <cs50.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[])
{
if (argc < 2 || only_digits(argv[1]) == false || argc > 2) // check for th correct input
{
printf("usage: ./caesasr key \n");
}
else
{
int key = atoi(argv[1]);
string plaintext = get_string("plaintext: ");
int x = strlen(plaintext);
char cyphertext[x + 1];
for (int i = 0; i < x; i++)
{
cyphertext[i] = rotate(plaintext[i], key);
}
printf("cyphertext: %s\n", cyphertext);
}
}
//make a function bool only_digits to check for input is a single digit between 0-9
bool only_digits(string s)
{
if (s[0] > 47 && s[0] < 58 && strlen(s) == 1)
{
return true;
}
else
{
return false;
}
}
//make a function char rotate(char c, int n) that rotate c by n on the alpahbet
// cout = (cin -65 + n)%26 +65 (uppercase)
// cout = (cin -97 + n)%26 +97 (lowercase)
// cout = cin (other)
char rotate(char c, int n)
{
if (c > 64 && c < 91)
{
c = ((c - 65 + n) % 26 + 65);
}
if (c > 96 && c < 123)
{
c = ((c - 97 + n) % 26 + 97);
}
else
{
return c;
}
return c;
}
CLI outputs, question marks and chars added randomly to the cyphertext个
我不知道问号和随机字符是从哪里来的; 它似乎只适用于5个字母的输入; DEBUG命令会发现一切工作正常,直到打印出最后一封输出信,然后突然添加了随机字符.
编辑:将第21行更改为
char cyphertext[x];
个
没有解决问题