0

Hello I'm not too experience with c++ but I've learned some of the basics. I tried making a small txt file encryption program however my output prints one too many times to the 2nd txt file. This occurs both when encrypting and decrypting.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;

char path1[256], path2[256];
	int EnORDe;
	char a,b;
	char newline='\r\n';

void encrypt();
void decrypt();

int main ()
{
	cout<< "what is the path to the text file: ";
		gets(path1);
	cout<< "where do you want the new text file: ";
		gets(path2);
	cout << "would you like to encrypt or decrypt a file(1 or 2): ";
		cin>>EnORDe;
		
		
		cout<<newline;
	if(EnORDe == 1)
	{
		encrypt();
	}
	else if(EnORDe == 2)
	{
		decrypt();
	}
	
	
system("PAUSE");

return 0;
}
void encrypt()
	{

	ifstream text(path1);
	a=('a'+'A'-'b')/'5';
	ofstream myfile;
  myfile.open (path2);
	while(!text.eof())
	{	
		text.get(b);
		b+=a;
		myfile <<b;
	}
	myfile.close();

	return;
	}

void decrypt()
{
	
	
	ifstream text(path1);
	a=('a'+'A'-'b')/'5';
	ofstream myfile;
	myfile.open (path2);
	while(!text.eof())
	{
		text.get(b);
		b-=a; 
		myfile <<b;

	}
			myfile.close();
	return;
}

I believe my loop is simply running one too many times but I'm not sure how to fix it.
Thanks for any help.

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by jonsca
1

>while(!text.eof())
This is an off-by-one error because eof only returns true after you've attempted to read beyond end-of-file. So you'll have one final iteration of the loop where get fails, but you still process b (from the previous iteration). You can use the result of get as a condition, which is both correct and more concise:

while (text.get(b)) {
    // ...
}
1
gets(path1);

You can overrun your buffer with gets. Use fgets instead (or you can use cin.getline if you want to use the C++ standard library).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.