尝试从用户C ++输入的代码中删除注释 [英] Trying to delete comments from code inputed by user C++
本文介绍了尝试从用户C ++输入的代码中删除注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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';
INPUT
/*comment
comment*/
okay~
OUTPUT
//
okay
=============
=============
程序会删除/ * * /之间的所有内容,但不会删除/ /。
the program deletes everything between /* */ , but won't delete the / /. Am I missing something?
推荐答案
是的,您缺少两个反斜杠,
Yes, you're missing two backslashes,
其实,你应该使用
code.erase(first-1, second - first+2);
这是因为 string.erase(first,last)
删除[first,last)范围内的字符
this is happening because string.erase(first,last)
removes characters in range of [ first , last )
ie它包括第一个字符,但不包括最后一个字符。
i.e. it includes first but excludes last,
注意:字符串中的第一个字符由值0(不是1)表示。
Note : First character in string is denoted by value 0 ( not 1 ).
我希望有助于
获取更多信息,请参阅此网页
这篇关于尝试从用户C ++输入的代码中删除注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文