Extraction between two barriers.

Yeah, so I've written this code to extract everything that is between "/*" and "*/". Unfortunately it doesn't work, I would be happy I someone would fix or tell me what I did wrong. Thanks in advance guys.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>

using namespace std;

int main () {

    int x = 0;


    string line = "This is /*a comment */";

    for( x=0; x<line.length(); x++) {
        if((line.at(x++)=='/') && (line.at(x++)=='*'))
            do {
                line.at(x++);
                cout << line.at(x);

            }while(line.at(x)!='*' && line.at(x+1)!='/');

    }

     return 0;

    }
Last edited on
Generally, you do not want to increment the counter inside a for loop.

The x defined on line 12 (which is not initialized) hides the x defined on line 8 (which is initialized.) So, it's quite likely that the junk in your uninitialized x is greater than line.length() so that the body of the for loop is never entered.


Last edited on
Fixed it, and edited it in the post. But I still have a major bug to fix.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

int main()
{
    std::string line = "This line contains /*a comment*/ in it." ;

    auto beg = line.find( "/*" ) ;
    if( beg != std::string::npos )
    {
        beg += 2 ;
        const auto end = line.find( "*/", beg ) ;
        if( end != std::string::npos )
        {
            const std::string comment = line.substr( beg, end-beg ) ;
            std::cout << '\'' << comment << "'\n" ;
        }
    }

    // TODO: take care of nested comments:
    // "This line contains /*a /*nested*/ comment*/ in it." ;
}
JLBorges, sorry but that code doesn't work for, maybe it's because I work in code blocks.
> maybe it's because I work in code blocks.

Perhaps you are not compiling with -std=c++11

With C++98, on lines 8 and 12, replace auto with std::size_t.

1
2
3
4
5
6
7
// auto beg = line.find( "/*" ) ;
std::size_t beg = line.find( "/*" ) ;

// ...

    // const auto end = line.find( "*/", beg ) ;
    const std::size_t end = line.find( "*/", beg ) ;

Topic archived. No new replies allowed.