Search code examples
c++stringvisual-c++erase

Trying to delete comments from code inputed by user 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?


Solution

  • 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