Write a program that accepts a string input from the user and reverses the contents of the string. Your program should work by using two pointers. The “head” pointer should be set to the address of the first charter in the string and “tail” pointer should set to the address of the last charter in the string.

#include<iostream>
#include<string>

using namespace std;

int main() {
    string str;
    char *head, *tail, *cstr;
    int i = 0;

    cout << "Enter a string: ";
    getline(cin, str);

    cstr = new char[str.size() + 1];
    strcpy_s(cstr,sizeof(cstr), str.c_str());

    head = &cstr[0];
    tail = &cstr[str.size() - 1];

    cout << "String inverted is: ";

    while (*head != '\0') {
        cstr[i] = *tail;
        *tail--;
        *head++;
        i++;
    }

    cout << cstr;

    cout <<"\n";

    return 0;
}

I am getting a linking error stating buffer is too small how to fix this
Thanks

>>I am getting a linking error stating buffer is too small
There is no such linking error. Post the exact error message.

>>strcpy_s(cstr,sizeof(cstr), str.c_str());
That is wrong because sizeof(any pointer) is always 4 on a 32-bit compiler. what you want is str.size().

>> *tail--;
>> *head++;

remove the stars because you want to increment the pointers, not the character to which they point.

I think the point of the assignment is not to create a copy of the string that is reversed, but to reverse the input string. Using a head and a tail pointer, swap the char that each point to, then advance each towards the middle. Be sure to stop when the two pointers are no longer in sequence.

And, to update the pointers, don't put the * in front of the variable. *tail-- changes the value of the char pointed to, tail-- changes the address that tail points to.

Does the problem really mean to use the C++ string type, or a char array based string? It really doesn't make much difference, other than finding the location of the last char.

If you have to use pointers I would rather suggest you to use C-strings (character based/array of characters) instead of C++-strings as a C-string actually is an array and an array's name can be used as a constant pointer it will be easier to implement it this way ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.