【问题标题】:Trying to delete comments from code inputed by user C++试图从用户 C++ 输入的代码中删除注释
【发布时间】:2014-10-05 05:05:00
【问题描述】:
string code;
cout << "Enter code\n";
getline(cin, code, '~');

size_t comment = code.find('/*');
size_t second = code.find('*/', comment);
size_t first = code.rfind('/*', comment);


code.erase(first, second - first);


cout << code << '\n';

输入

/*comment

comment*/

okay~

输出

//

okay

=============

程序会删除 /* */ 之间的所有内容,但不会删除 / /。我错过了什么吗?

【问题讨论】:

  • 我很惊讶您没有收到关于将两个字符放在字符文字中的编译器警告。您应该使用双引号 (") 来表示您要查找的字符串。
  • 并且您应该非常仔细地测试包含不完整 cmets 或包含 /* 的 cmets 的输入。

标签: c++ string visual-c++ erase


【解决方案1】:

是的,您缺少两个反斜杠,

其实你应该使用

code.erase(first-1, second - first+2);

这是因为 string.erase(first,last) 删除了 [ first , last ) 范围内的字符

即它包括第一个但不包括最后一个,

注意:字符串中的第一个字符由值 0(不是 1)表示。

希望对你有帮助 更多信息请参考this webpage

【讨论】:

  • 我的代码(second - first)+2和你的代码second - first+2有什么不同吗?
  • @Rustam 好吧,你能证明你的代码在做什么吗?就像我说的那样,这件作品没有任何问题,实际上,first-1 应该是第一个参数而不是first,只需尝试运行您的代码,您就会了解它。
  • 你认为你可以像'/*'这样在单引号中表示两个字符吗?
【解决方案2】:

试试这个:

size_t comment = code.find("/*");        
size_t second = code.find("*/", comment); // here it returns the index from where `*/` starts so you      should also delete these two charater that why i added 2 in erase function.
size_t first = code.rfind("/*", comment);


code.erase(first, (second - first)+2);  
cout << code << '\n';

【讨论】:

  • 您正在从代码中删除字符(它们是源代码的一部分)并且缺少一个字符(准确地说,是第一个反斜杠),请参阅我的答案。
  • @DigitalBrain 你跑了吗..?
  • @DigitalBrain 在 c++ 11 中的工作 fyn。我也在这里检查为字符串code.find("/*"); 而不是code.find('/*');
  • 我的错!我刚刚在提问者的代码中添加了 +2 并执行了,但是您的代码仍然可以咬人,我的意思是 49 年后它会咬人。
猜你喜欢
  • 2011-05-23
  • 2016-07-27
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
相关资源
最近更新 更多