Reputation: 128
So I have run a problem while trying to convert text from a file into a Caesar Cipher code. The content seem to be converted properly but near the end of the file it seem to dump some error at the end.
Question: What is the error causing to add the \FF to the end of the file?
Content of the Original File:
After Encryption :
as you can see from the picture I get the following added to the file \FF
this is the following code for Caesar Cipher...
void file_encription()
{
std::string filename = "alpha.dat";
ifstream inputFile( filename.c_str() );
string plaintext;
do
{
plaintext += inputFile.get();
}
while(inputFile);
//string with the whole file saved...
//string for the file plaintext
std::string &ciphertext = plaintext;
std::int decipher;
//Caesar Cipher code...
std::cout << "please enter a number...";
cin >> decipher;
int shift = decipher % 26
for(int i = 0; i < ciphertext.size(); ++i)
{
if (islower(ciphertext[i]))
{
ciphertext[i] = (ciphertext[i] - 'a' + shift) % 26 + 'a';
}
else if (isupper(ciphertext[i]))
{
ciphertext[i] = (ciphertext[i] - 'A' + shift) % 26 + 'A';
}
}
std::cout <<"your file was converted and saved as: decrypted_text.txt" << endl;
ofstream finale("decrypted_text.txt");
finale << ciphertext << endl;
finale.close();
cin.get();
return BegginingPage();
}
Upvotes: 0
Views: 2501
Reputation: 1637
You are also reading eof (-1 / 0xFF) with this here:
do
{
plaintext += inputFile.get();
}
while(inputFile);
use:
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
or
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string str = buffer.str();
and btw you should call the file after encryption encrypted_text not decrypted_text ;)
Upvotes: 3