1

I came across this question on here and had a further question about the answer give (I can't comment since I'm new to stackoverflow). The guy who answered it seems to be right about replacing << >> for cin and cout. But the problem I'm having is that all the semi-colons won't show up in the new output file.

I know that while std::getline(input, command, ';') erases all semicolons, but theyre supposed to be put back with the else statement at the end, but it isn't being replaced when I run it. And if I omit ';' out of the getline statement everything in the output file messes up.

How do you make it show that the semi-colon does show?

void print(ifstream& input,ofstream& output)
{
    bool first = true;
    std::string command;
    while(std::getline(input, command, ';'))
    { // loop until no more input to read or input fails to be read
        if (command.find("cin")!= std::string::npos)
        { // found cin somewhere in command. This is too crude to work. See below
            size_t pos = command.find("<<"); // look for the first <<
            while (pos != std::string::npos)
            { // keep replacing and looking until end of string
                command.replace(pos, 2, ">>"); // replace with >>
                pos = command.find("<<", pos); // look for another 
            }
        }
        else if (command.find("cout")!= std::string::npos)
        { // same as above, but other way around
            size_t pos = command.find(">>"); 
            while (pos != std::string::npos)
            {
                command.replace(pos, 2, "<<");
                pos = command.find(">>", pos);
            }
        }
        if (! first)
        {
            output << command; // write string to output
        }
        else
        {
            first = false;
            output << ';' << command; // write string to output
        }
    }
}
Community
  • 1
  • 1
Deegeeek
  • 25
  • 1
  • 5

1 Answers1

0

The problem is here:

        if (! first)
        {
            output << command; // write string to output
        }
        else
        {
            first = false;
            output << ';' << command; // write string to output
        }

In the first iteration, the else branch gets executed and a semicolon is printed.

In any later iteration, the if branch is executed, which does not print a semicolon.

The fix is easy: Swap the two lines starting with output <<.

nomadictype
  • 700
  • 4
  • 11
  • Thanks you. It seems to be working now. However, a semi-colon appears now at the beginning of the txt file I was testing. All the semicolons that were omittted with getline comeback, but a new one appears as the first character in the file. – Deegeeek Nov 04 '16 at 16:56
  • Actually fixed it. In the `if(! flag)` statement I just added and `&& !(line.find("#") != string::npos))` – Deegeeek Nov 04 '16 at 17:07