2
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

cynthiao
  • 35
  • 3
  • Here is a solution to read variable input via cin: http://stackoverflow.com/questions/201992/how-to-read-until-eof-from-cin-in-c – LordOfThunder123 Oct 06 '14 at 05:12
  • I can give you loop, but problems that could arise due to `//` in code is another problem, which is not at all mentioned here. – The Mean Square Oct 06 '14 at 05:46
  • What exactly are you building, I answered [ your previous question ](http://stackoverflow.com/questions/26199788/trying-to-delete-comments-from-code-inputed-by-user-c), I think it's going to be buggy – The Mean Square Oct 06 '14 at 06:01
  • @DigitalBrain a program to read a user's input (code) then remove all comment lines, any extra spaces (anything more than 1 space) and count all tokens. then display the edited code. – cynthiao Oct 06 '14 at 06:04
  • That's great, good job – The Mean Square Oct 06 '14 at 06:05

1 Answers1

1

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

The Mean Square
  • 234
  • 1
  • 9