Click to See Complete Forum and Search --> : string parsing still...


lir
July 14th, 2005, 11:25 AM
Hey guys,

I have a config file which it's first few lines are # commented and I want to skip them and start "anazlying" or basically doing string parsing stuff on the rest of the file..

so I've opened the file and i did something like this:

fp is the filepointer, str is the string im getting each line with.

code
...
...
while (getline(fp, str)) {
if ( !str.find_first_of("#") ); {
cout << str << endl;
}
}

i basically want to do my parsing inside the if statement on everything but the commented lines, so i figured id look for them, and when i dont match them then ill be working on the non-commented lines.
but it doesnt work that way when i compile it, i just see the entire file printed out...

any ideas for a simple way of doing this?

thanks.

mitakeet
July 14th, 2005, 11:40 AM
If it is the first character this will work:

if (str[0] != '#')...

NoHero
July 14th, 2005, 11:42 AM
You have a bug in your code: Remove the semicolon after the if statement otherwise the block with the out won't belong the if statement:

while (getline(fp, str)) {
if ( !str.find_first_of("#") )/* no ; here */ {
cout << str << endl;
}
}

After reading a line from the config file I would remove any space that is in front of the real line. This will also make the cut out of the comment lines easier. Imagine such a line:

seta motd "Hello"
seta sv_strictAuth "0"

Thus I would make it this way:

while (getline(fp, str))
{
while ( isspace(str[0]) )
{ // Remove spaces
str.erase(0, 1);
}
if ( str[0] != '#' )
{
cout << str << endl;
}
}

jlou
July 14th, 2005, 11:43 AM
while (getline(fp, str)) {
if ( !str.find_first_of("#") ); {
cout << str << endl;
}
} The semicolon in red means that your if statement has no effect
find_first_of returns string::npos (basically -1) if the string is not found and the index if it is found. Since this is not a boolean test, it is confusing to use the boolean operator! If you are trying to check to see if the return value is zero, it would be better to use:if ( str.find_first_of("#") == 0 ) If you are just checking to see whether the first character is #, it would be better to just check the first character, instead of wasting time on the entire string:if ( !str.empty() && str[0] == '#' )

[Edit] - Beaten, but make sure you check for an empty string before looking at str[0].

lir
July 14th, 2005, 11:56 AM
thanks you guys,
i learned alot from this post (like always :) ).

the semicolon there was a typo mistake since i wrote that
piece of code on the fly, i was probably not paying attention, but thanks :)

ill check it when i get home.
lir.