Skip comments in text file?

Is there any way to skip comments in text file by putting a // or something I'm pretty sure fortran has something similar and you use a # in the text file.
when you're doing file IO? No.
Yes when I'm doing file IO. That's not the answer I wanted to hear but I can accept it thanks!!
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>
#include <sstream>

std::istream& get_line_strip_comments( std::istream& stm, std::string& str )
{
    if( std::getline( stm, str ) )
    {
        auto pos = str.find( "//" ) ;
        if( pos == 0 ) return get_line_strip_comments( stm, str ) ;
        else if( pos != std::string::npos ) str.erase(pos) ;
    }
    return stm ;
}

int main()
{
    std::istringstream stm( R"(
this is a line with no comments
// this is a comment line
some text // and then a comment
more text / / this is not a comment // but this is\n)" ) ;

    std::string str ;
    while( get_line_strip_comments( stm, str ) ) std::cout << str << '\n' ;
}

http://ideone.com/DG45Kl
i'd be surprised if any language natively does this.

assuming you're reading your lines into a std::string then something like this would 'ignore' them:

1
2
3
4
5
6
7
8
9
10
11
12
std::string lineInput;

// read the line and stick contents in lineInput
if( ! (lineInput[0]=='/' && lineInput[1]=='/') )
{
    // do your stuff in here
}
else
{
    // line is 'ignored'
}

closed account (3qX21hU5)
Yes there is a way, I have no idea why mutexe said there wasn't...

Here is a very minor example. Just check if the first character of the line in the file is a #, if it is skip that line. This is only a minor example and needs more work but I didn't want to do it all for you ;p. Specifically you need to take care of any white spaces that come in front of things.

In this example I used '#' for the character but you can easily modify it to look for // instead by using if (line[0] == '/' && line[1] == '/') continue; other other methods of doing this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream file("myfile.txy");
    string line;
    while (getline(file, line))
    {
        // Skips the line if the first character is a '#'. If there is spaces or whitespace before it it wont skip it
        // So you might want to consider making something that trims the whitespaces infront of everything.
        if (line[0] == '#') continue;

        // You other stuff goes here
    }
}
Last edited on
that's pretty much exactly what i've just said??

and when i said there isn't a direct way i meant you had to write some code to do it.
Last edited on
closed account (3qX21hU5)
when you're doing file IO? No.


Sorry I took that as meaning no there isn't a way to do it...
no worries dude :)
Topic archived. No new replies allowed.