[英]It's about implementing the Caesar-cipher code to encrypt the input given by the user
該代碼接受要編碼的輸入(字符串)和來自用戶的鍵,以便當將鍵添加到輸入時,輸入將增加給定鍵的數量。 對於前。 如果鍵為2,則輸入A更改為C,b更改為d,依此類推。
我已經寫了相同的代碼,但無法獲得輸出。
int main()
{
int x,i,y,c;
char text[20];
printf("enter the plaintext:");
gets(text);
printf("enter the key: ");
scanf("%d",&x);
for (y=0;y<strlen(text);y++)
{
if (text[i]>='a'&&text[i]<='z'&&text[i]>='A'&&text[i]<='Z' )
{
int c=(int)text[i]+x;
printf("%c\n",text[i]);
}
}
}
我得到的結果是空白。 請幫助我。
您的提案中有很多問題,需要檢查輸入是否成功,您要在y而不是i上進行迭代,您需要計算新的char代碼,但不打印它
這里是一個更正的建議:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char text[100];
printf("enter the plaintext:");
if (fgets(text, sizeof(text), stdin) != NULL) {
int key;
printf("enter the key: ");
if (scanf("%d", &key) == 1) {
int i;
for (i=0; text[i] != 0; ++i)
{
if (isalpha(text[i]))
putchar(text[i] + key); /* may not be printable */
else
putchar(text[i]);
}
}
}
return 0;
}
編譯與執行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:the sentence to encode
enter the key: 3
wkh vhqwhqfh wr hqfrgh
pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:Alea jacta est
enter the key: 2
Cngc lcevc guv
有趣的是,32不是編碼大寫字符的好鍵:
pi@raspberrypi:/tmp $ ./a.out
enter the plaintext:THE FIVE BOXING WIZARDS JUMP QUICKLY.
enter the key: 32
the five boxing wizards jump quickly.
您初始化了y變量而不是i變量
嘗試這個 :
對於(i = 0; i <strlen(text); i ++){...}
注意 :
如果使用以下標志-Wall -Wextra -Werror編譯代碼,則可以幫助您更多地了解可能存在的錯誤,例如未使用的變量。
示例:gcc -Wall -Werror -Wextra youprogram.c -o輸出
您不僅有其他錯誤,
因此,我建議您解決問題的方法:(所有輸出字符均可打印)
#include <stdio.h>
#include <string.h>
int main(void)
{
char text[250];
size_t i;
int key;
printf("Enter the plaintext : ");
if (fgets(text, sizeof(text), stdin) != NULL)
{
printf("Enter the key : ");
scanf("%d", &key);
for(i = 0; i < strlen(text); i++)
{
if (text[i] >= 'a' && text[i] <= 'z')
putchar((((text[i] - 'a') + key) % 26) + 'a');
else if (text[i] >= 'A' && text[i] <= 'Z')
putchar((((text[i] - 'A') + key) % 26) + 'A');
else
putchar(text[i]);
}
}
return (0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.