Trying to delete comments from code inputed by user C++

不想你离开。 提交于 2019-12-14 03:59:03

问题


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?


回答1:


Yes, you're missing two backslashes,

Actually, you should use

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

this is happening because string.erase(first,last) removes characters in range of [ first , last )

i.e. it includes first but excludes last,

Note : First character in string is denoted by value 0 ( not 1 ).

I hope that helps for more information refer this webpage




回答2:


try this :

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';


来源:https://stackoverflow.com/questions/26199788/trying-to-delete-comments-from-code-inputed-by-user-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!