对于凯撒密码加密,我有这个代码。该程序使用用户编写的文本。但我希望从文本文件中读取它并运行。
#include<stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int key,i;
char [30];
clrscr();
printf("\n enter plain text : ");
gets(data);
printf("\ enter key value : ");
scanf("%d",&key);
{
for (i=o;i<strlen(data);i++) {
if (data[i]==' ') {}
else
{
if (data[i]>='x')
{
data[i]=data[i]-26;
}
data[i]=data[i]+key;
}
}
}
printf("your cipher text is : %s",data);
getch();
}
最佳答案
您刚刚是从某处复制并粘贴此代码吗?
正如其他人已经指出的那样,您的代码存在一些相当大的问题,因此我将尝试讨论他们在整个过程中没有提到的问题。首先,您应该将 main
声明为 int
。返回值告诉您程序是否正确退出,这不仅仅是约定。
这是您的原始代码,已格式化。我删除了 conio.h
因为它已被弃用多年,而且您在这里不需要它。它所做的只是为您清除屏幕,您可以使用 System("CLS");
来完成此操作,尽管 here是一篇很棒的文章,已在 SO 上分享过多次,解释了为什么您应该避免使用它。
#include<stdio.h>
#include<string.h>
int main()
{
int key,i;
// original: char [30];
// I'm guess you copied and pasted wrong?
char plainText[30];
printf("\n enter plain text : ");
gets(data);
printf("\nenter key value : ");
scanf("%d",&key);
// You had brackets here, essentially creating an unnecessary
// block of code.
for(i=o;i<strlen(data);i++)
{
// Where did the "data" variable come from? You haven't declared it
// and you're trying to get its length in this for loop
if (data[i]==' ')
{
// ?
}
else
{
if (data[i]>='x')
{
// Instead of this approach I would go with a modulus operation
// If you're not familiar with modular arithmetic I really recommend you look
// it up. It's absolutely essential in cryptography. It's central to both
// symmetric and asymmetric key cryptography.
data[i]=data[i]-26;
}
// This is the heart of the Caesar cipher right here. This is where you're actually
// shifting the characters, so it's a literal Caesar cipher
data[i]=data[i]+key;
}
}
// Again, you haven't declared "data" so you can't call it. I'm guessing you didn't
// try to compile this program because it is teeming with errors GCC, Clang, and VC++
// would have caught immediately
printf("your cipher text is : %s",data);
getch();
// Remember to make your "main" function return an <code>int</code>. This value is
// very important, especially when your program gets called by another program because
// it's how your program communicates that it ran successfully, or something went
// wrong. In that case you could set a specific error code to know exactly
// what went wrong and were
// Example:
int x = 1;
if (x == 1)
exit(4);
// This program would now exit with a status of 4, which you would then know was due
// to this function. This was a contrived example, but hopefully you get the gist
return 0;
}
关于c - 如何使用 C 语言中的文件编写凯撒密码加密代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43208711/