代码取得输入(字符串)要被编码并从用户,使得当键被添加到输入端的输入被增加给定键的量的密钥。对于前。如果密钥是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上,而不是我重复,你计算出新的字符代码,但你不要打印
这里更正建议:
#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 = 0; I <strlen的(文本);我++){...}
注意 : 如果你有以下标志-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);
}