0

I have a file similar to the one below

@
@
1 2 3
4 5 6
7 8 9

I want to ignore lines starting with an '@' character. My current code to parse the file is straightforward.

string line;
while(getline(in, line)) {
    if(line[0] == '@')
        continue
    // do something with line
}

The amount of @ tokens in the file will be small and will always occur at the beginning of the file, but I don't want to have to go through the if check after every read. I would rather read the header section in a separate function, then start reading the desired data without the need for the if check. How can I do this?

ChrisD
  • 674
  • 6
  • 15

2 Answers2

1

Of course you can do something like::

do{
    getline(in, line);
}while(line[0] == '@')

do{
    //do something with line
}while(/* not EOF*/)

But you might also be interested in the famous answer about branch prediction. It basically tells you that processors are usually very good at "guessing" the right outcome of an if-statement, especially if, as you stated, after a few lines the outcome will be always the same. So your version should not only be pretty much the same speed but also be valid in case there is another line starting with '@' later in your file.

Community
  • 1
  • 1
Anedar
  • 4,235
  • 1
  • 23
  • 41
0

Anedar is correct, you could also do:

string line;
while(getline(in, line)) 
{
    if(line[0] == '@'){
        continue;
        //do something
    }
    else{
        break;
    }
}

some people like do/while loops, some don't, whatever floats your boat or is the standard you have the write by. :)

lciamp
  • 675
  • 1
  • 9
  • 19