[英]Caesar Cipher C program not printing
Basically what the title says.基本上是标题所说的。 Can anyone tell me why my program won't print at the end?
谁能告诉我为什么我的程序最后不打印? As far as I can tell the for loop should be rotating each letter but at this point, I have no idea.
据我所知,for 循环应该旋转每个字母,但在这一点上,我不知道。
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int key;
bool keyValid = false;
while (keyValid == false)
{
printf("Enter rotation key: ");
scanf("%d", &key);
if (key >= 0 && key <= 26)
{
keyValid = true;
}
else
{
printf("Error - key must be in range 0 and 26. Try again. ");
}
}
// printf("Encrypting message (key = %d): %s \n", key, message);
if(keyValid == true) {
char message[80];
printf("Enter message to encrypt: ");
scanf(" %80[^\n]*s", message);
for(int i = 0; i < strlen(message); i++){
if (isupper(message[i])){
message[i]= (message[i] - 65 + key) & 26 + 65;
}
else if (islower(message[i])){
message[i]= (message[i] - 97 + key) & 26 + 97;
}
}
printf("%s", message);
}
return 0;
}
Your problem is here你的问题在这里
message[i]= (message[i] - 65 + key) & 26 + 65; ^ ^
The expression is evaluated as (message[i] - 65 + key) & 91
which most likely results in a unprintable character.该表达式被评估为
(message[i] - 65 + key) & 91
这很可能导致不可打印的字符。
You want你要
message[i] = ((message[i] - 'A' + key) & 26) + 'A';
or, even better, using modulus %
或者,更好的是,使用模数
%
message[i] = ((message[i] - 'A' + key) % 26) + 'A'; // keep the extra parenthesis!
message[i] = (message[i] - 'A' + key) % 26 + 'A';
The calculations being performed in the following lines produce non-printable results.在以下行中执行的计算产生不可打印的结果。
message[i]= (message[i] - 65 + key) & 26 + 65;
message[i]= (message[i] - 97 + key) & 26 + 97;
Replacing both lines with this should do the trick.用这个替换这两行应该可以解决问题。
message[i]= (message[i] + key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.