cynthiao
cynthiao

Reputation: 35

deleting ALL comment lines that start with // c++

string str;

cout << "Enter code\n";
getline(cin, str, '~');

    //some loop i can't figure out
        size_t nFPos = str.find('//');
        size_t second = str.find('\n', nFPos);
        size_t first = str.rfind('\n', nFPos);
        str.erase(first, second - first);
   //end unknown loop

INPUT

code

//comment

//COMMENT

code~

OUTPUT

code

//COMMENT

code

I cannot for the life of me figure out what kind of loop I should use for it to delete ALL comments starting with //. It's only deleting the first comment and bypassing everything else.

I've tried for, while, do while, and if

I can't figure it out

Upvotes: 2

Views: 983

Answers (1)

The Mean Square
The Mean Square

Reputation: 234

You should use

while(true)
    {
        size_t nFPos = str.find('//');        
        if(nFPos + 1)
        {
            size_t second = str.find('\n', nFPos);
            size_t first = str.rfind('\n', nFPos);
            str.erase(first, second - first);
        }
        else
        {
            break;
        }
    }   

as mentioned Here

While executing std::find(), If no matches were found, the function returns string::npos

which is defined as static const size_t npos = -1;

So whenever a match will be found it'll return the position of the first character of the first match, (so it'll be non -1 ).

If it is unable to find any match it'll return -1 and else section will be executed (because -1+1=0 and 0 is equivalent to false ), taking us out of the loop

Upvotes: 1

Related Questions