-1

i am currently working on a program whereby i can substitute alphabets in a text file(called plaintext.txt), along with a keyfile, and create a ciphertext when i run a command to mix them together. The working code is as shown below:

string text;
string cipherAlphabet;

string text = "hello";
string cipherAlphabet = "yhkqgvxfoluapwmtzecjdbsnri";

string cipherText;
string plainText;

bool encipherResult = Encipher(text, cipherAlphabet, cipherText);
bool decipherResult = Decipher(cipherText, cipherAlphabet, plainText);  

cout << cipherText;
cout << plainText;

Output for the above code will be below

fgaam
hello

However, i want to convert my "text" and "cipherAlphabet" into a string where i obtain the both of them through different text files.

string text;
string cipherAlphabet;


std::ifstream u("plaintext.txt"); //getting content from plainfile.txt, string is text
std::stringstream plaintext;
plaintext << u.rdbuf();
text = plaintext.str(); //to get text


std::ifstream t("keyfile.txt"); //getting content from keyfile.txt, string is cipherAlphabet
std::stringstream buffer;
buffer << t.rdbuf();
cipherAlphabet = buffer.str(); //get cipherAlphabet;*/

string cipherText;
string plainText;

bool encipherResult = Encipher(text, cipherAlphabet, cipherText);
bool decipherResult = Decipher(cipherText, cipherAlphabet, plainText);  

cout << cipherText;
cout << plainText;

However if i do this, i get no output and no error? Is there anyone out there that can help me with this please? Thank you!!

fabian
  • 5
  • 1

1 Answers1

1
std::ifstream u("plaintext.txt"); //getting content from plainfile.txt, string is text
std::stringstream plaintext;
plaintext << u.rdbuf();
text = plaintext.str(); //to get text

When you use the above lines of code to extract text, you are getting any whitespace characters in the file too -- most likely a newline character. Simplify that block of code to:

std::ifstream u("plaintext.txt");
u >> text;

Same change needs to be done to read the cipher.

If you need to include the whitespaces but exclude the newline character, use std::getline.

std::ifstream u("plaintext.txt");
std::getline(u, text);

If you need to be able to deal with multiline text, you will need to change your program a bit.

R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • Thank you for the fast reply! However, i would like to make use of the function's ability to read spaces in between strings too. for now, im just try to read with one line of string in the text file. i had some difficulty with reading spaces in text file using while and for loops before, and i came across this reading of text file without using loops. – fabian Oct 18 '17 at 16:44
  • @fabian, in that case, you need to use `std::getline`. `std::getline(u, text);`. That will include any spaces but will exclude the ending newline character. – R Sahu Oct 18 '17 at 16:47