homework help decrypting

Hi, I need help with my coding and what is wrong with it. I am making a function where I have to read from a file called contents.txt and decipher the code a little. To decipher I have to eliminate all of the double characters and only make one, an example would be aaabbbyyy ---> aby . For some reason it is not couting the string deleted to the terminal, so I must have made a mistake I can't see. I am a beginner in C++, so can someone please help me step by step.

In the contents.txt file:
fousx.-..fpqefoub_bpq`foulropbffkeffpqlovsx
teihteilftt^kq^_rteioofqqlhl
tjctjcmujf`eefdd^ketjcll`hhbvltkpmu
wprezgwpr\\noamdwpr_\tiidbco6$f{


And this is my function so far:

string decrypt (string encrypted)
{

string decrypt1, decrypt2, deleted;
int i, pos;

ifstream contents;
contents.open("contents.txt");
contents >> encrypted;
while(!contents.eof()){
cout << encrypted;
contents >> encrypted;

}

for (i=0; i < encrypted.length(); i++)
{
if((pos=decrypt1.find(encrypted[i]))<0)
{
decrypt1 = decrypt1 + encrypted[i];
}

}

deleted = decrypt1.substr(0,3);

cout << deleted << endl;

return deleted;
}
Last edited on
Question: Are you required to remove all duplicates of a char from the whole file or per line?
If you are eliminating duplicates from the entire file then the following code will do this. If you only intend to remove duplicates from each line then you will need to use a local variable to ::readline and pass this through as a reference to ::isduplicate, then at the end of ::readline append the contents to m_result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <fstream>
#include <string>

using namespace std;

string m_result;

bool isduplicate(char c)
{
   return m_result.find(c) != string::npos;
}

void readline(string& line)
{
   if (!line.empty())
   {
      for (auto p = line.begin(); p != line.end(); ++p)
      {
         char c = *p;
         if (!isduplicate(c))
            m_result += c;
      }
   }
}

void readfile(const string& filename)
{
   ifstream fs;
   fs.exceptions(ifstream::badbit);

   try
   {
      fs.open(filename.c_str(), ifstream::in);
      if (fs.is_open())
      {
         string line;
         while (getline(fs, line))
            readline(line);
         fs.close();
      }
   }
   catch(ifstream::failure err)
   {
      // TO DO
   }
}

int main()
{
   readfile("c:\\temp\\contents.txt");
	
   return 0;
}
Topic archived. No new replies allowed.