Simple Encryption...

closed account (3872Nwbp)
Just to try to expand my skills, how basic they might be, I decided to try basic encryption/decryption. This is my start at encryption... And it IS basic. Haha.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	string given, encrypted;
	int length, key;
	
        // Input
	cout << "Please type what is to be encrypted:" << endl;
	getline(cin, given);

	length = given.length();    // Get length of string

	cout << endl << "Please enter the encryption key: ";
	cin >> key;        // number by which characters will be changed

	for(int a = 0; a < length; a++)         // the main loop
		encrypted[a] = given[a] + key;

         // Output
	cout << endl << "Your given text is: " << endl << encrypted << endl << endl;
	
	system("pause");
	return 0;
}


When I run this, I get an error message "string subscript out of range". I've tried things like converting the strings to char arrays, which have a whole other problem themselves, and by now, a few hours on google. Including staring at my screen and going through each line multiple times. I'm at a huge loss. Any help is well appreciated, including anything about my coding not really related to this problem.


The error message indicates that you are trying to write into encrypted to elements that do not exist. You can ensure the elements exist by setting

1
2
getline(cin, given);
encrypted = given;


right after you read into given; that will guarantee that encrypted is large enough to take all the new letters.


Alternatively

1
2
length = given.length();    // Get length of string
encrypted.resize(length);

Last edited on
line 23 encrypted[a] = given[a] + key;
you should know that encrypted[a] can hold data only from 0 to 255
you should know that encrypted[a] can contain data only from 0 - 255 see line 23
encrypted[a] = given[a] + key;
Last edited on
closed account (3872Nwbp)
@Moschops Thank you very much, that makes a lot of sense.

@tejashs And yes I do know that, thanks for the reminder.

Works fine now! Thanks guys!
Last edited on
Topic archived. No new replies allowed.