0

I have been asked to save my values to an external file in c++ I am having difficulty having my code access the .txt file and was wondering if anyone could identify what I am missing. In this case the code is taking a string from my .txt file and encrypting it in a very basic manner. For some reason I am getting a bunch of random characters as my original input when I would Like it to simple encrypt "John Doe"

# include<fstream>
#include<iostream>
#include <string>
using std::ifstream;
using std::ofstream;
using std::endl;
using namespace std;

int const LENGTH_OF_STRING = 10;

int main() {
    ifstream instream;
    ofstream outstream;

    instream.open("infile.txt");
    outstream.open("outfile.txt");

    char myMsg[LENGTH_OF_STRING];
    char encryption[LENGTH_OF_STRING];

    cout << myMsg; // this is returning a crazy string of characters therefore I must be missing the command to let the program know where to get the information from

    for (int i = 0; i < strlen(myMsg); i++) {
        int asciiNum = (int)myMsg[i];
        int newAsciiNum = asciiNum + 100;
        char newEncryption = (char)newAsciiNum;

        encryption[i] = newEncryption;
        outstream << myMsg[i] << " = " << asciiNum << "\t"
            << " new ascii number = " << newAsciiNum << "\t"
            << "New encrypted character = " << newEncryption << endl << endl;
    }

        outstream << endl << "encrypted message = " << encryption << endl << endl;

    instream.close();
    outstream.close();

    system("PAUSE");
    return 0;
}

Any help would be greatly appreciated

P.S. my infile.txt looks like:

myMsg = "John Doe";

encryption = " ";

  • 3
    You need to read the contents of the file into `myMsg`. You're not doing that. – NathanOliver Oct 26 '18 at 14:23
  • https://stackoverflow.com/help/mcve –  Oct 26 '18 at 14:25
  • That's what I assumed however I'm not sure what the best way to go about that is – Nick Janerico Oct 26 '18 at 14:25
  • 1
    See: https://stackoverflow.com/questions/20902945/reading-a-string-from-file-c – NathanOliver Oct 26 '18 at 14:25
  • Uninitialized variable myMsg; cout << myMsg; What will happen? –  Oct 26 '18 at 14:30
  • 2
    Possible duplicate of [Reading a string from file c++](https://stackoverflow.com/questions/20902945/reading-a-string-from-file-c) – Davis Herring Oct 26 '18 at 17:47
  • [How to copy a .txt file to a char array in c++](https://stackoverflow.com/q/18398167/608639). More generally, [c++ how to read file into character array site:stackoverflow.com](https://www.google.com/search?q=c%2B%2B+how+to+read+file+into+character+array+site%3Astackoverflow.com) – jww Oct 27 '18 at 07:57

0 Answers0