Menu

encrypting a string

2009-02-09
2012-09-26
  • anonymous nobody

    include <cstdlib>

    include <cstdio>

    include <cstring>

    define atoc static_cast<char>

    define ctoa static_cast<int>

    void crypt(int s,char a)
    {
    int i;
    for(i=0;i<s;i++)
    {
    if(ctoa(a[i])<126)
    {
    a[i]=atoc(rand())%130;
    }
    else
    {
    a[i]=atoc(ctoa(a[i])+1);
    }
    }
    for(i=s;i<s+50;i++)
    {
    delete(&a[i]);
    }
    }
    int main(int argc, char
    argv[])
    {
    char i[10];
    strcpy(i,"");
    printf("Enter 10 characters.\n");
    scanf("%s",i);
    crypt(10,i);
    printf("\n%s\n",i);
    system("PAUSE");
    return 0;
    }

    This code is supposed to take a string with a length of 10 and encrypt it using ASCII numbers. It works fine except for one thing: the printed string is 15 characters long, instead of 10. I have no ideas; any help?

    -JM

     
    • anonymous nobody

      Ah... I've solved the problem. I've always thought char a[10] made an array with 10 elements but it actually makes 11. Thus:

      include <cstdlib>

      include <cstdio>

      include <cstring>

      define atoc static_cast<char>

      define ctoa static_cast<int>

      void crypt(int s,char a)
      {
      int i;
      for(i=0;i<s;i++)
      {
      if(ctoa(a[i])<126)
      {
      a[i]=atoc(rand())%130;
      }
      else
      {
      a[i]=atoc(ctoa(a[i])+1);
      }
      }
      for(i=s;i<s+50;i++)
      {
      delete(&a[i]);
      }
      }
      int main(int argc, char
      argv[])
      {
      char i[9];
      strcpy(i,"");
      printf("Enter 10 characters.\n");
      scanf("%s",i);
      crypt(10,i);
      printf("\n%s\n",i);
      system("PAUSE");
      return 0;
      }

      produces the correct result.

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.