tags:

views:

45

answers:

1

hi all I'm having problems with my code.

the cipher actually works its just I get some odd three digit codes separated with slashes any help would be greatly appreciated heres my code

the codes look like this but have random numbers /354/233/645/810/236

    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "cs50.h"

    int i, len;
    string sentance, encrypted;
    int k, argvLen;

    int caesar (int k){

 printf("Hi I'm Ceaser! What would you like me to cipher?\n");

 sentance = GetString();
 len = strlen(sentance);
 char encrypted[len];

     for (i=0; i<len; i++) {
 if (sentance[i] >='a' && sentance[i] <='z') {
  encrypted[i] = ((sentance[i] - 'a' + k) % 26) + 'a';

  }
 else if (sentance[i] >='A' && sentance[i] <='Z') {
  encrypted[i] = ((sentance[i] - 'A' + k) % 26) + 'A';

     }
 else if (sentance[i] >=' ' && sentance[i] <= '@'){
  encrypted[i] = sentance[i];
 }

 }


 printf("%s", encrypted);
 return 0;
    };


    int main (int argc, const char * argv[]) {

 if (argc==2) {
  k = atoi(argv[1]);
  argvLen = strlen(argv[1]);
  for (i=0; i<argvLen; i++){
   if (isdigit(argv[1][i])){   
   caesar(k);
      }
   else {
   printf("please enter a number for the key!");
   return 1;
   }

     }

    return 0;

 }
    };
+3  A: 

You are not terminating the encrypted string properly.

You need:

  1. To make sure you have room for the terminating character, by using char encrypted[len + 1];.
  2. encrypted[len] = '\0'; after the loop.
unwind
Shouldn't it be `encrypted[len] = '\0';` after the loop ?
codaddict
@codaddict: Totally true, that was an editing error. Fixed, thanks.
unwind
Thank you very much for your input, it finally works now! I understand the bit about leaving space for the terminating char but what is part two doing is '\0' magic for a terminating character, which is then placed at the end of the string by using [len] as strings start from 0. Right?