I have to write a program to "encrypt and decrypted" some text.
For example if I input: FACHHOCHSCHULE
with a password of: TIGER
it should encrypt to: YIILYHKNWTACRI
which I got working but when I try to reverse the process I get numbers, letters and symbols. Please help.

#include <iostream>
#include <string>
using namespace std;
string encrypt(string,string);
string decrypt(string,string);

void main()
{
	cout<<"Code: ";
	string code;
	cin>>code;
	cout<<"Password: ";
	string pass;
	cin>>pass;
	int length=pass.length();
	char test=pass.at(0);
	string temp=encrypt(code,pass);
	cout<<"Encrypted Code: "<<temp<<endl;
	string temptwo=decrypt(code,pass);
	cout<<"Decrypted Code: "<<temptwo<<endl;
}

string encrypt(string s,string pass)
{
	string answer;
	int length=pass.length();
	int place=0;
	for(int i=0;i<s.length();i++)
	{
		int temp=(s.at(i)-char('A'))+(pass.at(place)-char('A'));
		if(temp>= 26)
			temp=temp%26;
			place++;
			temp=temp+char('A');
		if(place>=length)
			place=0;
		answer+=temp;
	}
	return answer;
}

string decrypt(string s,string pass)
{
	string answer;
	int length=pass.length();
	int place=0;
	for(int i=0;i<s.length();i++)
	{
		int temptwo=(s.at(i)-char('A'))-(pass.at(place)-char('A'));
		if(temptwo>= 26)
			temptwo=temptwo%26;
			place++;
			temptwo=temptwo+char('A');
		if(place>=length)
			place=0;
		answer+=temptwo;
	}
	return answer;
}

Recommended Answers

All 8 Replies

To start with, you're trying to decrypt the original input string!

string temp=encrypt(code,pass);
	cout<<"Encrypted Code: "<<temp<<endl;
	string temptwo=decrypt(code,pass);   ///should be (temp, pass)
	cout<<"Decrypted Code: "<<temptwo<<endl;

Fix that, and it works.

To start with, you're trying to decrypt the original input string!

string temp=encrypt(code,pass);
	cout<<"Encrypted Code: "<<temp<<endl;
	string temptwo=decrypt(code,pass);   ///should be (temp, pass)
	cout<<"Decrypted Code: "<<temptwo<<endl;

Fix that, and it works.

I tired that and got:
Code: FACHHOCHSCHULE
Password: TIGER
Encrypted Code: YIILYHKNWTACRI
Decrypted Code: FACHH5CHSC.;LE
Press any key to continue . . .

It seems to miss 2 letters.

The problem in decrypt is that you can possibly get a negative number from the subtraction

int temptwo=(s.at(i)-char('A'))-(pass.at(place)-char('A'));

so, besides your test of >= 26 as a result, you also need to handle the possibility of < 0 as a result.

how would you do that? please explain....

EDIT: Bad reply :)

got it five minutes later
if(temptwo<65)
temptwo=temptwo+26;

SOLVED

wait, why would it be temptwo<65? wouldn't it be temptwo<0

send the full complete script now to see if this is it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.