Ask your own question, for FREE!
Computer Science 9 Online
OpenStudy (anonymous):

write a c++ program to reverse the string using pointers? please help

OpenStudy (anonymous):

do you have a char buffer for the result?

OpenStudy (anonymous):

do you have to use char arrays or std::string?

OpenStudy (anonymous):

OK, here is an in-place solution: #include <iostream> void reverse(char* s) { const int n = strlen(s); for (int i = 0; i < n / 2; ++i) { char c = s[i]; s[i] = s[n - 1 - i]; s[n - 1 - i] = c; } } int main(int argc, char *argv[]) { char s[] = "hello, world"; reverse(s); std::cout << s << std::endl; return 0; }

OpenStudy (anonymous):

#include "stdafx.h" const int strLen=6; char szStart[strLen] = "Hello"; char szEnd[strLen] = ""; int _tmain(int argc, _TCHAR* argv[]) { //declare the pointers char* pszStart = szStart; char* pszEnd = szEnd; //make the destination pointer point to the end of the string, //-2 because of the end of string char. Without it we would copy the //string exactly reversed and the end of strign would be the first char //and we would see nothing :D pszEnd += strLen-2; //1) dereference the pointers //2) assign source char to destination char //3) decrease the destination pointer and, //4) increase the source pointer //5) lastly check we are not assigning the end of string char and if so quit while //check we are not at the end of the string while ((*pszEnd-- = *pszStart++) != NULL); return 0; }

OpenStudy (anonymous):

Of course this is really a c style app. Todo a c++ version of this really misses the point of c++. It is definitely overkill to use classes for tis type of problem but I suppose it cold be done. Char class, and a string reverser class. c++ is mainly used in larger systems to encapsulate complexity and simplify interfaces between modules.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!