yeah, you'd either need to use binary reading or writing, or you could try using text, but you'd need to make sure that everything can be read back from teh file correctly. for example, if one of your letters turns into a newline '\n' it'll throw off your entire file.
so you'd need to do something like this:
Code:
#include <iostream>
#include <fstream>
#include <string>
std::string encrypt(const std::string in);
int main()
{
std::string in;
std::fstream file("test.dat",std::ios::out|std::ios::trunc);
std::cout<<"Enter a word: ";
getline(std::cin,in,'\n');
/*
* I'm "encrypting" the word, and outputting the result to console and
* to file to read from later.
*/
in=encrypt(in);
std::cout<<in.c_str()<<std::endl;
file<<in.c_str();
/*
* I'm closing and clearing the stream, then Re-Opening it for reading
* in text mode
*/
file.close();
file.clear();
file.open("test.dat",std::ios::in);
/*
* Now I get the result back from the file, en(de)crypt it, and then
* output it to the console
*/
getline(file,in,'\n');
in=encrypt(in);
std::cout<<in<<std::endl;
return 0;
}
std::string encrypt(const std::string in)
{
std::string key="5b4s3v4rs618srge6yt7ra4vy7r8a9et7yne85r71gera5";
short int len;
register short int x;
register short int y;
std::string retval;
/*
* I'm finding out the length of the string now to save processor time
* later, and I'm making sure there's enough space in retval to hold
* the result (which will be the same length as the string
*/
len=in.length();
retval.resize(len);
/*
* here's the heart of the 'encryption'. what it does is an XOR
* encryption, and if the resulting character isn't something that can
* be seen on a screen (or read from a file correctly), then it moves
* to the next character in the key, and re-encrypts the character in
* the word.
*/
for(x=0,y=0; x<len; x++,y++)
{
retval[x]=in[x]^key[y];
if(!isgraph(retval[x]))
{
x--;
}
}
return retval;
}
edit: you can use that code, but you're gonna wanna fix up the encrypt function, because I left some possible big time run-time errors in there...