打破的替代方案? 我对C++很陌生,而且我被告知不要使用“中断”语句。我很好奇除了“休息”还有什么选择?(使用下面的代码示例) void remove_注释(ifstream&fileIn、ofstream&fileOut) { 弦线; 布尔标志=假; bool-found=false; 而(!fileIn.eof()) { getline(fileIn,line); if(line.find(“/*”)
有时需要休息——如果不休息,你可能会撞到前面的东西,伤到自己 你也可能会因为思考不好,然后以一种甚至6个月后你都无法理解的神秘方式解决问题而伤害自己 最后——不管是谁告诉你不要用“休息”这个词。给他一个休息的机会——永远不要在他/她/它旁边停下来征求意见打破的替代方案? 我对C++很陌生,而且我被告知不要使用“中断”语句。我很好奇除了“休息”还有什么选择?(使用下面的代码示例) void remove_注释(ifstream&fileIn、ofstream&fileOut) { 弦线; 布尔标志=假; bool-found=false; 而(!fileIn.eof()) { getline(fileIn,line); if(line.find(“/*”),c++,C++,有时需要休息——如果不休息,你可能会撞到前面的东西,伤到自己 你也可能会因为思考不好,然后以一种甚至6个月后你都无法理解的神秘方式解决问题而伤害自己 最后——不管是谁告诉你不要用“休息”这个词。给他一个休息的机会——永远不要在他/她/它旁边停下来征求意见 顺便说一句——处理缩进和卷曲——不太好。您可以重写循环 for (int i=0; i < line.length() && !(i+1 < line.length() && (l
顺便说一句——处理缩进和卷曲——不太好。您可以重写循环
for (int i=0;
i < line.length() &&
!(i+1 < line.length() && (line.at(i) == '/') && (line.at(i + 1) == '/'));
++i)
{
fileOut << line[i];
}
fileOut<<endl;
for(int i=0;
i FielOUT 我认为使用<代码> Buffe<代码>是很好的,但是如果你的任务是不做它的工作,那么我们就不用它来做这个问题。同样的问题可以通过使用不同C++的不同的控制流语句来解决。这个问题也可以在没有<代码>破解< /代码>的情况下解决。我想让你把你的函数分解成一个中心函数和几个辅助函数。因为我不想代替你来解决这个问题,所以我只是用指令和一些“伪代码”来帮助你
您有一个由注释和非注释部分依次组成的输入文本。您希望在循环中执行以下操作:
// I refer to non-commented text as "writable"
writable_begin = 0
while (writable_begin < text_len)
{
writable_end, comment_type = find_next_comment_begin(writable_begin);
write_out_text(writable_begin, writable_end);
if (comment_type == singleline)
writable_begin = find_singleline_comment_end(writable_end);
else
writable_begin = find_multiline_comment_end(writable_end);
}
//我将未注释的文本称为“可写”
可写_begin=0
while(可写\u begin
您必须了解如何实现我在伪代码中使用的帮助函数/方法,它们可以轻松地实现而不中断。如果您使用帮助函数解决问题,您还可以得到比当前使用复杂控制流语句的意大利面代码更好的解决方案。许多错误很容易隐藏在此类代码中
提示:你的助手函数将在循环中搜索注释文本的结尾,但是你可以简单地使用return
退出助手函数并返回结果,而不是break
。你可以而且应该重写该循环。Mankarse给出了一个选项,但在这个选项中有所有那些奇怪且难以理解的条件e用于循环
你应该学会利用标准库的力量。例如,这个代码将从C++代码行注释中删除所有存储在行<代码>中的字符串:
// Find the first instance of two forward slashes in the line
// and return an iterator to that.
auto begin_comment = line.find("//");
// We found it! Remove all characters from that point on
if (begin_comment != std::string::npos)
line.erase (begin_comment, line.end());
fileOut << line << std::endl;
//查找行中两个正斜杠的第一个实例
//并返回一个迭代器。
自动开始注释=行。查找(“/”);
//我们找到了!从该点上删除所有字符
if(begin_comment!=std::string::npos)
line.erase(begin_comment,line.end());
fileOut谁告诉你不要使用break
?这是过早结束循环的自然方式。顺便说一句,而(!fileIn.eof())
是不好的做法。你必须检查eof()
在执行输入操作之后,而不是之前。与@Barmar alread所说的相关:有一个名为goto
的终极关键字,但我肯定更喜欢break
而不是goto
。似乎摆脱break
的最简单方法是使用行。查找(“/”)
而不是内部循环。德·摩根定律可能有助于澄清条件的第二部分。
// Find the first instance of two forward slashes in the line
// and return an iterator to that.
auto begin_comment = line.find("//");
// We found it! Remove all characters from that point on
if (begin_comment != std::string::npos)
line.erase (begin_comment, line.end());
fileOut << line << std::endl;
for (int i=0; i < line.length(); i++)
{
if(i<line.length())
if ((line.at(i) == '/') && (line.at(i + 1) == '/'))
break;
else
fileOut << line[i];
}