I hate writing class methods. Anyway, I'd really appreciate any help I could get with this, as the program's due tomorrow. -_- I wrote a nice little reverse_string function, now I have to put it in a class called apstring. So I prototyped this function with a return type of apstring, and basically it creates an string called ReversedString which essentially is myCstring reversed, and then returns ReversedString. Problem is, I keep getting this error (I'm using Microsoft Visual C++ 5.0):
index out of range: 0 string:
Assertion failed: 0 <= k && k < myLength, file D:\Program Files\DevStudio\SharedIDE\bin\APSTRING.CPP, line 139
This is where the error is:
Code:
char& apstring::operator[](int k)
// precondition: 0 <= k < length()
// postcondition: returns copy of the kth character
{
if (k < 0 || myLength <= k)
{
cerr << "index out of range: " << k << " string: " << myCstring
<< endl;
assert(0 <= k && k < myLength); // line 139
}
return myCstring[k];
}
And here's the method I wrote:
Code:
apstring apstring::reverse_string() const
// description: returns the string reversed
// precondition: the string must contain at least one printable character
// postcondition: returns the string reversed or returns a blank string (just \0) if the precondition is not met
{
// declares variables
int Subscript1, Subscript2 = myLength - 1;
apstring ReversedString1;
// reverses string
for(Subscript1 = 0; Subscript1 <= myLength; Subscript1++)
{
if(Subscript1 == myLength)
{
ReversedString1[Subscript1] = '\0';
break;
}
ReversedString1[Subscript1] = myCstring[Subscript2];
Subscript2--;
}
return ReversedString1;
}// end Reverse_string
And finally, this is the prototype in the header file:
public:
apstring reverse_string() const;
I attached the class in a zip file should anyone decide to give me some help. Again, I would really appreciate any help!
...
I'm thinking that the problem lies within the subscript operator overload, but if Subscript1 stores an int value, then why won't it work correctly? : |