#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;
}
我不知道问号和随机字符从哪里来; 它似乎只适用于 5 个字母的输入; debug 命令发现一切都按预期工作,直到打印最后一个输出字母,然后突然添加随机字符。
编辑:将第 21 行更改为
char cyphertext[x];
没有解决问题
这意味着您的字符数组没有以“ ”结尾以使其成为字符串。
printf("%s", ...)
需要一个字符串。这里最简单的解决方法是将其添加到 for
中的 main()
循环之后:
cyphertext[n] = '\0';