【发布时间】:2016-11-04 03:15:13
【问题描述】:
我在这里遇到了this question,并对给出的答案提出了进一步的问题(我无法发表评论,因为我是 stackoverflow 的新手)。回答这个问题的人似乎是正确地将 > 替换为 cin 和 cout。但我遇到的问题是所有分号都不会出现在新的输出文件中。
我知道 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