I/O 流字符串操作(正确的 Cin/cout 运算符 <</>>)

I/O Stream String Manipulation (Correct Cin/cout operators <</>>)

我在这里遇到 并且对给出的答案有进一步的疑问(我无法发表评论,因为我是 Whosebug 的新手)。回答它的人似乎将 << >> 替换为 cincout 是正确的。但我遇到的问题是所有分号都不会出现在新的输出文件中。

我知道 while std::getline(input, command, ';') 擦除所有分号,但它们应该在最后用 else 语句放回去,但它没有被替换当我运行它。如果我省略 ';'在 getline 语句中,输出文件中的所有内容都乱七八糟。

如何让它显示分号确实显示?

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
        }
    }
}

问题在这里:

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

在第一次迭代中,执行 else 分支并打印分号。

在以后的任何迭代中,都会执行 if 分支,这 不会 打印分号。

修复很简单:交换以 output << 开头的两行。