Search code examples
c++encryptioniostreamfstreamtext-files

c++ text decoder decoding more than asked for


Im working on a text file decoder along with an encoder, they work off of two different text files. The decoder prints the decoded message underneath the encoded message but it also prints a bunch of other stuff as well. How do i fix this

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
  ifstream fin; // input file
  string line;
  ofstream fout;

  //open output file
  fout.open("secret.txt", ios::app);
  if (!fout.good()) throw "I/O error";

  // open input file
  fin.open("secret.txt");
  if (!fin.good()) throw "I/O error";

  // read input file, decode, display to console
  while (fin.good()) {
    getline(fin, line);

    for (int i = 0; i < line.length(); i++) // for each char in the string...
      line[i]--; // bump the ASCII code down by 1

    fout << line << endl; // display on screen
  }

  // close file
  fin.close();

  return 0;
}

the text file from the encoder reads

Uftujoh234

Ifmmp!nz!obnf!jt!cpc

Dmptfe!

Uftujoh

which decodes to

Testing123

Hello my name is bob

Closed

Testing

this is all the extra stuff it also prints in the text file

Sdrshmf012
Gdkknlxm`ldhrana
Bknrdc
Sdrshmf
Rcqrgle/01
Fcjjmkwl_kcgq`m`
Ajmqcb
Rcqrgle
Qbpqfkd./0
Ebiiljvk^jbfp_l_
@ilpba
Qbpqfkd
Paopejc-./
Dahhkiuj]iaeo^k^
?hkoa`
Paopejc
O`nodib,-.
C`ggjhti\h`dn]j]
>gjn`_
O`nodib
N_mncha+,-
B_ffigsh[g_cm\i\
=fim_^
N_mncha
M^lmbg`*+,
A^eeh

Solution

  • The extra data you see is actually valid output from decoding the data in "secret.txt".

    I'm not sure if this is what you want, but are you aware that you are reading and writing to the same file each time you run your application?

    You'll append more and more "decoded" data to the file, and therefore you get the extra output you are referring to.


    Also, there is an issue with your while-loop.

    fin.good () will remain true until some of the error bits has been set inside of fin, though it will enter the loop one time too much since you should check to state of the stream immediately after your call to getline (fin, ...).

    Currently the reading will fail but you will still process the "unread" data.


    std::getline will return the stream object, and since a std::istream (as well as std::ostream) implicitly can be converted to a boolean to check it's current state you should use that as your loop-condition.

    Change your loop into something as the below and see if that solves your problem.

      while (getline (fin, line))
      {
        for (int i = 0; i < line.length(); i++) // for each char in the string...
          line[i]--; // bump the ASCII code down by 1
    
        fout << line << endl; // display on screen
      }