user3769362
user3769362

Reputation: 21

Wrap around in C for Ceasar's Code

Hey guy's last time I posted I was a bit sloppy. Hopefully this time it'll look a lot better . Thank you for your time if you decide to help me. I really need it. Anyways heres the question. I need to have wrap around for my Code and i heard you can do it with modulus but I am not sure i am doing it correctly because I do not get the right results.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main () {
   char s[200]; //blank array//
   int mess;
   printf("Generations have wondered how the Ceasar Code works\n");
   printf("Please choose a number to mess up (encode) the current file\n");
   scanf("%d", &mess);
   mess = mess % 26;
   FILE *ptof = fopen("Rock.txt", "r");
   char a[200];//fill array with characters from file//
   int i=0;
   while( (a[i++]=fgetc(ptof)) != EOF && i < 89) { //get character from file//
   }
   a[i] = '\0'; /* null-terminate the string */
   i = 0;

   do{
      printf("%c",a[i++]);
   } while  (a[i] != '\0'); /* print until hit \0 */
   int j = 0;
   for (j = 0; j < 89; j++){
      s[j] = a[j] + mess;
   }
   printf("%s\n", s);

   fclose(ptof);
   return 0;
}

Upvotes: 1

Views: 107

Answers (2)

William Pursell
William Pursell

Reputation: 212298

There's a lot of room for improvement here. Do you really want to map printable characters into (potentially) non-printable characters? Or do you merely want to do a ceaser shift on letters in the alphabet? Why the arbitrary limit of 90 characters of input? Using scanf is never a good idea (in 20 some years writing code, I have never used it since I left school). Passing the shift on stdin rather than as an argument makes it hard to use your program as a filter. For instance, it would be really nice if you could take a string and shift it by 4, then by 13, then by 9 and see that you get the original text back. (eg < file ceaser 4 | ceaser 13 | ceaser 9 | diff - file should report no diffs).

Here's a few ideas:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

FILE *
xfopen( const char *path, const char *mode )
{
        FILE *ifp = fopen( path, mode );
        if( ifp == NULL ) {
                perror( path );
                exit( 1 );
        }
        return ifp;
}

int
main( int argc, char **argv )
{
        int mess = argc > 1 ? strtol( argv[1], NULL, 10 ) % 26 : 13;
        FILE *ptof = argc > 2 ? xfopen( argv[2], "r" ) : stdin;
        int c;

        while( ( c = fgetc( ptof )) != EOF ) {
                if( isupper( c ))
                        c = 'A' + ( c - 'A' + mess ) % 26;
                if( islower( c ))
                        c = 'a' + ( c - 'a' + mess ) % 26;
                putchar( c );
        }
        return 0;
}

Upvotes: 1

Kevin L
Kevin L

Reputation: 1066

s[j] = a[j] + mess needs a modulo operation as well

Upvotes: 3

Related Questions