1

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

}
6
  • @ameyCU The word Hello Commented Oct 24, 2015 at 15:00
  • 4
    p = ( p - 'a' ) + shift % 26 + 'a'; --> p = ( p - 'a' + shift) % 26 + 'a'; Commented Oct 24, 2015 at 15:01
  • 2
    Minor: Space not needed in " %d". "%d" by itself will skip leading white-space. Commented Oct 24, 2015 at 15:04
  • @chux wow I can't believe I didn't notice that... thank you so much. Commented Oct 24, 2015 at 15:05
  • @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. Commented Oct 24, 2015 at 15:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.