Understanding strings a bit more

Hi,

I had this function which caused an error, but I want to know why.
It is used to strip strings which may look like this: "text", text, "" or <absolutely nothing>. They originate from a csv file (example line: "text",text,"",)
I kept getting an error when I started processing a second file, which may have completely empty fields (,,,,,)
I found the problem: if I don't use line nr 4 to demand that a string is longer than 1 character before it can be stripped, I get an error.
My question: why is it that it has to be longer than 1 (why isn't length 1 good enough)? I think it must have something to do with '\0', right?

1
2
3
4
5
6
7
8
9
10
11
EditedString csvFile::strip(EditedString str_in)    //strips the outer characters and removes the inner doubled ones
{
    EditedString str = str_in;
    if(str.size()>1)
        if((str.find('\"')==0) && (str.rfind('\"')==(str.size()-1)))
        {
            str.erase(0,1);
            str.erase(str.size()-1,1);  //strip the outer characters
        }
    return str;
}
why is it that it has to be longer than 1
Well, you always erase 1 character. But if there's no character what's that erase function supposed to do then?

Further more if str.size() == 0 you're trying to erase 1 character from a negative index. I think that's worth an error?
Size will never be zero, because of '\0', no? But it probably isn't allowed to remove '\0'
You made me realize that I always remove 2 characters, so the string needs to be longer than 2 (so at least 2 characters and the '\0' character)

I think I cracked it by now :D
Hm, I don't know what 'EditedString' actually is. A std::string doesn't depend on the '\0' at the end and hence has a size() == 0.
EditedString is the standard string class with some extra functions. Hm, so size can be zero... Alright, got it
I confused it with the array of characters (http://www.cplusplus.com/doc/tutorial/ntcs/)
Last edited on
Topic archived. No new replies allowed.