开发者

Strange unwanted three digit code printouts from caesar cipher

The cipher code actually works; it's just that I get some odd three digit codes separated with slashes too. Any help would be greatly appreciated. Here's 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') {
 开发者_JS百科 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;

 }
    };


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜