【问题标题】:I/O Stream String Manipulation (Correct Cin/cout operators <</>>)I/O 流字符串操作(正确的 Cin/cout 运算符 <</>>)
【发布时间】:2016-11-04 03:15:13
【问题描述】:

我在这里遇到了this question,并对给出的答案提出了进一步的问题(我无法发表评论,因为我是 stackoverflow 的新手)。回答这个问题的人似乎是正确地将 > 替换为 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
        }
    }
}

【问题讨论】:

  • std::getline 函数不会改变文件的内容。
  • 请使用您遇到问题的代码编辑您的问题。
  • 道歉。已编辑。
  • 这是实际代码吗? look_for_arrow1 变量似乎未声明。
  • 使用链接中的代码进行了编辑。它用正确的文本和更正的 cin/cout 运算符吐出一个输出文件,但没有分号。我假设 getline 正在执行此操作,但我认为最后的 else 语句将其放回原处。

标签: c++ string iostream fstream


【解决方案1】:

问题出在这里:

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

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

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

解决方法很简单:交换以output &lt;&lt; 开头的两行。

【讨论】:

  • 谢谢。它现在似乎正在工作。但是,我正在测试的 txt 文件的开头现在出现了一个分号。 getline 恢复时省略的所有分号,但新的分号作为文件中的第一个字符出现。
  • 实际上已修复它。在我刚刚添加的if(! flag) 语句中和&amp;&amp; !(line.find("#") != string::npos))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多