0

Hey all I am new to c++ and I am working on a simple project which takes an inputted string and outputs the string in reverse. I coded the program using what I remembered from programming classes I took years ago however I keep getting a warning for using strcpy and it will not compile on the command prompt and I am not exactly sure the alternative way. Please help. Here is the code:

#include <iostream>
#include <string>

using namespace std;

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

    cout << "Please enter a string: " << endl;
    cin >> reverse;

    cstr = new char[reverse.size() + 1];

    strcpy(cstr, reverse.c_str());
    head = &cstr[0];
    tail = &cstr[reverse.size() - 1];

    cout << "The string inverted is: " << endl;

    while (head <= tail) {
        temp = cstr[i];
        cstr[i] = *tail;
        *tail = temp;
        *tail--;
        *head++;
        i++;

    }
    cout << cstr;
    cout << "\n";

    return 0; 

}
python paradise
  • 91
  • 1
  • 2
  • 8

3 Answers3

1

You almost certainly want to use std::string, and do your best to forget that you ever even heard of strcpy. I'd probably write something on this general order:

std::string forward;
std::cin >> forward;

std::string reverse{forward.rbegin(), forward.rend()};

std::cout << "The string reversed is: " << reverse;

If you prefer to reverse the string in place, the standard library has an std::reverse for that:

std::string reverse;
std::cin >> reverse;

std::reverse(reverse.begin(), reverse.end());

std::cout << "The string reversed is: " << reverse;
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

I define _CRT_SECURE_NO_WARNINGS in all my projects to shut these warnings up.

since standard strcpy can cause buffer overflow and memore corruption you can use strcpy_s instead.

Zlixine
  • 184
  • 2
  • 15
-2

You could use memcpy to copy your string. strcpy probably uses memcpy internally though.

mileippert
  • 177
  • 8
  • He asked for a C++ alternative. I don't think you are answering that. –  Sep 11 '16 at 00:21