问题
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