if i is -1 you will return buf[-1] - out of bounds access
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
in this case using i == stringlength will give you the out of bound access
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
How do I make the print function use printf() to output the name of the string, the string literal, and the size of the string literal with the three all displayed on one line per string object?
What is string name?
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
like
?Code:printf("%s: %s(%d)\n", name, buf, stringlength);
But why do you need a printf if you trying to write in C++?
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
Going back to your operator[], you fixed the wrong thing. I'm guessing you tried it and an exception was thrown? You have to try to understand why that happens. When I said it was obvious, I didn't mean it would necessarily be obvious when you first look at it (otherwise you wouldn't have coded it that way), I just meant that once you realized what it was it would make sense. It sounds like you still don't know what the flaw was.
So your fix was to return sink instead of throwing an exception in the first if statement. That wasn't where the problem was. The problem was the if. Pick a number and run it through the if and see where you get. You should always do this in your mind or on paper to test the if to see if it does what you want. Let's say the stringlength is 8 and the user wants the character at position 3. Follow your if in the earlier code and see what gets executed.
>> isn't printf used in C++?
It can be, but cout is generally used instead.
I made some changes:
Also, how do I make a +operator() that acts as a unary operator for the string class.Code:char& String::operator [](int i) const { if(i < 0 || i> stringlength) return sink; else return buf[i]; } char& String::operator [](int i) { if(i < 0 || i>stringlength) return sink; else return buf[i]; }
You mean like
*edit* Often, such operators are better declared not as members, so thatCode:String String::operator+ (const String & other);
you could group those functions with others of similar type -- namely:
Code:String operator+ (const String & left, const char* right);
Last edited by CodeMonkey; 08-06-2007 at 11:28 PM.
"If you tell the truth, you don't have to remember anything"
-Mark Twain