为什么我的代码不接受不包含字符a-z A-Z 0-9的字符串? 如果加密这个转移例如“aaaaa [[[[[[”, 我收到一个错误。 我想要代码,以便它也可以接受空格或任何东西,并跳过不是a-z,A-Z,0-9的那些。
为什么我的最后一个声明不能做到这一点?
例如:
"a a" shift 1
应该是
"b b"
我的代码:
#include <stdio.h>
int main (){
char word[20];
int rotx;
printf("enter string\n");
scanf("%s", word);
printf("enter rotations\n");
scanf("%d", &rotx);
encrypt(word, rotx);
return 0;
}
void encrypt (char word[], int rotx){
int w = strlen(word) - 1;
int i = 0;
for ( ; i <= w; i++)
if ((word[i] + rotx) >= 65 && (word[i] + rotx) <=90)
{
word[i] += (rotx);
}
else if ((word[i] + rotx) >= 97 && (word[i] + rotx) <=122)
{
word[i] += (rotx);
}
else if ((word[i] + rotx) >= 48 && (word[i] +rotx) <= 57)
{
word[i] += (rotx);
}
else if ((word[i] + rotx) > 90 && (word[i]+rotx) <97)
{
word[i] = 64 + (rotx - (90-word[i]));
}
else if ((word[i] + rotx) > 122)
{
word[i] = 96 + (rotx - (122-word[i]));
}
else
{
continue;
}
}
答案 0 :(得分:2)
如果使用scanf()
将字符串作为输入,则会插入字符串,忽略空格。所以如果你输入
hello world
仅
hello
被scanf视为输入。所以使用fgets()
答案 1 :(得分:2)
老实说,我不知道你在做什么。 这是我认为caesar密码基于我阅读的维基百科的代码。 如果有人发现非语法上的缺陷,这对于演示原因是有害的让我知道。
PS,考虑阅读“https://www.kernel.org/doc/Documentation/CodingStyle”,它会帮助你(和我)很多。 PS:如果我打破上面的编码风格,它不会让我成为伪君子,我只选择最适合我的风格。
花了5分钟来编码。
#include <stdio.h>
#include <string.h>
void encrypt(char *res, char *word, int rot)
{
int len;
int i;
int tmp;
len = strlen(word);
for (i = 0; i < len; ++i) {
tmp = word[i] - 'a';
tmp += rot;
tmp %= ('z' - 'a');
res[i] = tmp + 'a';
}
res[len] = 0;
}
void decrypt(char *res, char *word, int rot)
{
int len;
int i;
int tmp;
len = strlen(word);
for (i = 0; i < len; ++i) {
tmp = word[i] - 'a';
tmp -= rot;
tmp %= ('z' - 'a');
res[i] = tmp + 'a';
}
res[len] = 0;
}
int main()
{
char word[20];
char result[20];
char decode[20];
int rot;
printf("enter a word: ");
scanf("%s", word);
printf("enter rotations: ");
scanf("%d", &rot);
encrypt(result, word, rot);
printf("result: %s\n", result);
decrypt(decode, result, rot);
printf("decode: %s\n", decode);
return 0;
}
答案 2 :(得分:1)
您的scanf()
不会读取空格,因此请将其更改为以下格式
scanf("%[^\n]", word);
请不要使用gets()
,因为它已被弃用且使用起来很危险,尤其是当您的目标是提供安全性时。
此外,您不需要这样精心设计的encrypt()
函数,下面给出的循环足以实现Caesar Cipher,
for ( ; i <= w; i++)
{
word[i] +=rotx;
}