1
votes

This program takes a a file name which contains a particular sentence and shifts by a certain amount.

if I have Hello and shift by 22 it should be Dahhk, This worked properly when I didn't enter the file name and had the file name in the program manually like

ifp = fopen( "input.txt", "r" );

However when I have the user enter the file name and the input is Hello and shift by 22 the output becomes D{‚‚…

ifp = fopen( name, "r" );

I tried using scanf("%s", name);

and I tried using fgets(name, sizeof(name), stdin);

both produce the same results

I am not sure how to fix this issue.

#include <stdio.h>

#define MAX_LEN 100

void decode( char *sentence, int shift );

int main( void )
{
  FILE *ifp;
  FILE *ofp;

  char str[MAX_LEN];
  int shift_by = 0;
  char name[100];

  printf("Program name: \n");
  scanf("%s", name);
  printf( "Please enter shift by and press enter\n" );
  scanf( " %d", &shift_by );

  ifp = fopen( name, "r" );
  ofp = fopen( "output.txt", "w" );

  if ( ifp == NULL )
  {
    printf( "FILE doesnt open" );
    return 1;
  }

  while ( fgets( str, MAX_LEN, ifp ) != NULL )
  {
    decode( str, shift_by );
    fprintf( ofp, " %s", str );
  }

  fclose( ifp );
  fclose( ofp );
  return 0;
}

void decode( char *sentence, int shift )
{
  int i = 0;
  char p;

  while ( p = sentence[i] )
  {
    if ( ( p >= 'a' ) && ( p <= 'z' ) )
    {
      p = ( p - 'a' ) + shift % 26 + 'a';
    }

    if ( ( p >= 'A' ) && ( p <= 'Z' ) )
    {
      p = ( p - 'A' + shift ) % 26 + 'A';
    }

    sentence[i] = p;
    i++;
  }

}
1
@ameyCU The word Hello - lodam
p = ( p - 'a' ) + shift % 26 + 'a'; --> p = ( p - 'a' + shift) % 26 + 'a'; - chux - Reinstate Monica
Minor: Space not needed in " %d". "%d" by itself will skip leading white-space. - chux - Reinstate Monica
@chux wow I can't believe I didn't notice that... thank you so much. - lodam
@lodam : you could request chux to post that as an answer, and you can mark the answer as valid, so that question status can be tied as solved for the benefit of future users. - Whirl Mind

1 Answers

1
votes

OP's code has a small error:

// p = ( p - 'a' ) + shift % 26 + 'a';
p = ( p - 'a' + shift) % 26 + 'a';

Curiously OP coded correctly with

p = ( p - 'A' + shift ) % 26 + 'A';

The hint was "Hello" --> "D{‚‚…" worked for uppercase, yet not lowercase.