-2

So say I have a txt file that goes like:

#unwanted line
something=another thing
something2=another thing 2
#unwanted_line_2=unwanted
something3=another thing 3

and I am reading it with

getline(inFile,astring,'=');

to separate a something from its value (inside a while loop). How do I skip the entire lines that start with # ? Also I'm storing this in a vector, if it is of any matter.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Why are you using `'='` as delimiter for lines? That's wrong. Otherwise just check if input wasn't empty and `astring[0] != '#'`. You probably want to read the whole line first, and parse that key=value stuff using another `std::stringstream xy(astring);` – πάντα ῥεῖ Oct 21 '22 at 18:56
  • Related: https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it – πάντα ῥεῖ Oct 21 '22 at 19:00
  • 3
    Read the line. Read the first character. Ignore the ones that start with #. You can't simply skip it, you have to read the sucker to know you can skip it. – user4581301 Oct 21 '22 at 19:03

1 Answers1

2

Use getline() without a delimiter to read an entire line up to \n. Then check if the line begins with #, and if so then discard it and move on. Otherwise, put the string into an istringstream and use getline() with '=' as the delimiter to split the line (or, just use astring.find() and astring.substr() instead).

For example:

while (getline(inFile, astring))
{
    if (!asstring.empty() && astring[0] != '#')
    {
        istringstream iss(astring);
        getline(iss, aname, '=');
        getline(iss, avalue);
        ...
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770