简体   繁体   English

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

[英]Can't figure out an issue with Caesar Cipher in C++

I have some trouble figuring out what the problem is with my code. 我很难弄清楚我的代码出了什么问题。 My task is to write the Caesar cipher in a file. 我的任务是在文件中写入Caesar密码。 It seems to display additional symbols that should not be there (from time to time), but it is otherwise working well. 它似乎显示了不应该出现的其他符号(有时),但是在其他方面效果很好。 Here is what it looks like http://puu.sh/kC04F/2fc1bbd048.jpg and Here's the code, thanks in advance ^^ 这是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;
}

The issue is char conv[20]; 问题是char conv[20]; contains garbage. 包含垃圾。 Then you fill it up with the conversion but you never add a null terminator to the end to indicate the end of the string. 然后用转换填充它,但不要在结尾处添加空终止符以指示字符串的结尾。 cout seems to be handling the garbage differently than fwrite so you get a difference on your output to the file versus what is on the screen. cout似乎在处理垃圾方面与fwrite有所不同,因此您输出到文件的内容与屏幕上显示的内容有所不同。 To fix this change: 要解决此更改:

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

To

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM