-2

I'm new to this forum as well as C++ in general, and I'm making a program that imports text from one file, changes it a bit, and then moves the changed text over to another file. Anyways, I didn't have much of a problem changing the text over, but the way that I tried to bring the newlines over didn't work, and I have no idea why. The program imported the text over but didn't import the newlines. Thanks. I could really use some help.

    char fileChars;
    ifstream codedMessage; 
    ofstream decodedMessage;

    cout << "Decoding File" << endl;

    codedMessage.open("secretMessage.txt");
    decodedMessage.open("decipheredMessage.txt"); 

    if (codedMessage.fail() ) {
           cerr << "Error..." << endl;
           exit(1);
    }

    while (!codedMessage.eof()){ 
      codedMessage >> fileChars;
      if (fileChars == '\n') {
        decodedMessage << "\n";
      } else if (fileChars == '~') {
        decodedMessage << ' ';
      } else {
        decodedMessage << ++fileChars;
      }
    }

    cout << "Closing Files." << endl;
    codedMessage.close(); 
    decodedMessage.close();
Dogcam
  • 13
  • 3
  • 3
    Define "didn't work". What outcome did you expect, what did you observe, and how do the two differ? – Igor Tandetnik Apr 01 '18 at 19:21
  • https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –  Apr 01 '18 at 19:28
  • Sorry, I meant to say that it didn't work because it didn't copy the newline's between the 2 files. Thanks you guys! – Dogcam Apr 01 '18 at 20:16

3 Answers3

1

The problem is in the way you try to get single char from istream. Try to use fileChars = codedMessage.get(); instead of codedMessage >> fileChars;.

Anton Todua
  • 652
  • 3
  • 15
0

This might work

ifstream codedMessage;
ofstream decodedMessage;

cout << "Decoding File" << endl;

codedMessage.open("secretMessage.txt");
decodedMessage.open("decipheredMessage.txt"); 

char my_character ;

while (!codedMessage.eof() ) 
{
    codedMessage.get(my_character);
    cout << my_character;
    if (my_character == '\n'){
            decodedMessage << '\n';
        }
    }
    else if (my_character == '~') {
        decodedMessage << ' ';
    } 
    else {
        decodedMessage << ++my_character;
    }
}

cout << "Closing Files." << endl;
codedMessage.close(); 
decodedMessage.close();
Loz
  • 41
  • 5
0

Read a line at a time with getline, and write out the text for the line a character at a time, followed by a newline:

std::string line;
while (std::getline(codedFile, line)) {
    for (auto ch : line) {
        if (ch == '~')
            decodedFile << ' ';
        else
            decodedFile << ch + 1;
    }
    decodedFile << '\n';
}

I used ch + 1 instead of your ++ch; I prefer that, because incrementing ch suggests that the incremented value somehow matters. But that's a minor point.

Pete Becker
  • 69,019
  • 6
  • 64
  • 147