I've been playing around with encrypting a string, and I've got it working great except for one thing. If the values entered are larger than the variables have room for then the program messes up. Obviously this is bad, so I need some way to truncate the strings that are input so that they fit in the space I've allocated.
Here's what I've got right now (it's not that long so I'll just post the whole thing):
Code:
#include <iostream>
#include <conio.h>
using namespace std;
#define STRLEN 256
#define CODELEN 10
int main()
{
int j,i,codeLen; // j and i are for the for loops, codeLen is the length of the encryption code
char str[STRLEN]; // stores the string to be encrypted
char code[CODELEN]; // stores the code
for (;;)
{
cout << "Enter a string to be encrypted (exit to quit) -> ";
cin.getline(str, STRLEN);
if (!strcmp(str, "exit"))
break;
cout << "Enter an enctyption code (up to " << CODELEN << " characters) -> ";
cin.getline(code, CODELEN);
for (i=0;str[i] != '\0';i++)
{
for (j=0;code[j] != '\0';j++)
{
str[i] ^= code[j];
}
if (str[i] == '\0')
str[i] = (char)255;
}
codeLen = j-1;
cout << "Your string encrypted is: " << str << endl;
for (i=0;str[i] != '\0';i++)
{
if (str[i] == (char)255)
str[i] = '\0';
for (j=codeLen;code[j] >= 0;j--)
{
str[i] ^= code[j];
}
}
cout << "And then decrypted again: " << str << endl;
cout << endl;
}
cout << endl << "Press any key to continue...";
getch();
return 0;
}
Now I thought that cin.getline() was supposed to limit the length of the input, but as far as I can tell I was wrong, because it really doesn't seem to be working.