Acutally, I don't understand how it works since you approaches a memory which is not yours to access.
Like people told you before size is not the element indicator because we start from 0.
Acutally, I don't understand how it works since you approaches a memory which is not yours to access.
Like people told you before size is not the element indicator because we start from 0.
I changed it completely I put a while loop in instead I think the code is ok now cheers.
sorry walla I don't understand what you mean.
What is your current code?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Ok it's probably still wrong ha.. works fine though.
Code:using namespace std; string mirrorends(string s) { int size = s.size(); string mirror; int i = 0; while (s[i]==s[size -(i+1)]) { mirror = mirror + s[i]; i++; } return mirror; } int main(int argc, char *argv[]) { string a = mirrorends("racecar"); cout << a << endl; system("PAUSE"); return EXIT_SUCCESS; }
why not use iterators? std::string provides forward and reverse iterators, accessible with begin/end and rbegin/rend. you could start a for loop, initializing two iterators with begin and rbegin, and increment both each time through the loop. as long as the values referred to by the iterators are the same, you continue the loop and add the current value of the iterator you received from begin to the end of your string.
>> Ok it's probably still wrong ha.. works fine though.
Works fine for which inputs? I liked your for loop better, honestly. The bug you had was really simple. Did you figure out what it was or did you just want to try the while loop? Note that your while loop actually has the same type of problem as your for loop did (you have to know when to stop).
>> why not use iterators?
For something this simple that is a learning exercise it's probably not necessary, especially since it's unlikely that caffrea4 has been introduced to them. Also note that he or she would have to solve the same problem for your pseudocode as in the for and while loops, so it wouldn't be any more correct than what is there already.