Sunday, July 12, 2009

I need help with pointers in C++?

Write a function that takes a C string as an input parameter and reverses the string. The function


should use two pointers, 'front' and 'rear'. The 'front' pointer should initially reference the first


character in the string, and the 'rear' pointer should initially reference the last character in the


string. Reverse the string by swapping the characters referenced by 'front' and 'rear', then increment


front to point to the preceding character, and so on, until the entire string is reversed. Write a


main program to test your function on various strings of both even and odd length.


*/


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





void swap_char(int* pFront, int* pRear);





int main(){


string sentence;


int *pFront, *pRear;


cout %26lt;%26lt; "Type in a sentence of less than 40 characers: \n";


cin %26gt;%26gt; sentence;


swap_char(pFront, pRear);


return 0;


}


void swap_char(int* pFront, int* pRear){


while(pRear %26gt; pFront)


{


string sentence;


char temp;


%26amp;temp =

I need help with pointers in C++?
Some tips:





pFront and pRear should be char*, not int*.





You need to set pFront and pRear to something before calling swap_char. However, the problem statement says swap_char's argument should be a "C string". I assume it wants you to use character array, and not a C++ string object. Inconvenient as that may be, you need this signature:





void swap_char(char * const s);





(i.e., const pointer, non-const data)





You might think you should have this call in main() :


swap_char(sentence.c_str());





That won't work, though, because c_str() returns a const char*, and swap_char needs to modify the character array. You need to declare a character array, then copy the c_str from sentence. Also, there's no need to limit the input to 40 characters, or any length.





So you need something like this:





getline(cin,sentence);


char *line = new char[sentence.length()+1];


memcpy(line,sentence.c_str(),sentence....


swap_char(line);





Why getline instead of cin's operator%26gt;%26gt;, you ask? Try them both, you'll see.





Also, #include %26lt;cstring%26gt; for memcpy. And when you're done, don't forget to: delete [ ] line;





I'll leave the guts of swap_char for you to work out, but this should get you going in the right direction.

survey research

No comments:

Post a Comment