gpt4 book ai didi

c++ - 无法找出 C++ 中 Caesar Cipher 的问题

转载 作者:行者123 更新时间:2023-11-28 06:02:22 25 4
gpt4 key购买 nike

我很难弄清楚我的代码有什么问题。我的任务是将凯撒密码写入文件。它似乎显示了不应该出现的额外符号(有时),但它在其他方面运行良好。这是它的样子http://puu.sh/kC04F/2fc1bbd048.jpg这是代码,提前致谢^^

#include<iostream>
#include<conio.h>
#include<cstring>
#include<stdio.h>
using namespace std;
int main ()
{
char ch[20];
char conv[20];
int i;
cout<<"Enter a word "<<endl;
gets(ch);
int otm;
cout<<"Enter shift "<<endl;
cin>>otm;
int c=strlen(ch);

for(i=0; i<c; i++)
{
conv[i]=ch[i]+otm%26;
}

for(i=0; i<c; i++)
{
cout<<conv[i];
}

FILE *stream;
char ime[]="probe.txt";

stream=fopen(ime, "w");
fwrite(conv, strlen(conv), 1, stream);
fseek (stream, 0, SEEK_SET);

cout<<endl;
fflush(stream);
fclose(stream);


system ("pause");
return 0;
}

最佳答案

问题是 char conv[20]; 包含垃圾。然后你用转换填充它,但你永远不会在末尾添加空终止符来指示字符串的结尾。 cout 处理垃圾的方式似乎与 fwrite 不同,因此输出到文件的内容与屏幕上的内容不同。要修复此更改:

for (i = 0; i<c; i++)
{
conv[i] = ch[i] + otm % 26;
}

for (i = 0; i<c; i++)
{
conv[i] = ch[i] + otm % 26;
}
conv[c] = '\0';

关于c++ - 无法找出 C++ 中 Caesar Cipher 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com