Sgt Memop
Sgt Memop

Reputation: 1

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. 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 ^^

#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;
}

Upvotes: 0

Views: 93

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

The issue is 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. 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';

Upvotes: 1

Related Questions