c++中strcpy的替代品

alternative for strcpy in C++

本文关键字:替代品 strcpy c++      更新时间:2023-10-16

嘿,我是c++的新手,我正在做一个简单的项目,它需要输入字符串并反向输出字符串。我用几年前我从编程课上记住的东西编码了这个程序,但是我一直得到使用strcpy的警告,它不会在命令提示符上编译,我不确定替代方法。请帮助。下面是代码:

#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; 
}

您几乎肯定想使用std::string,并尽力忘记您甚至从未听说过strcpy。我可能会这样写:

std::string forward;
std::cin >> forward;
std::string reverse{forward.rbegin(), forward.rend()};
std::cout << "The string reversed is: " << reverse;

如果你想在适当的位置反转字符串,标准库有一个std::reverse:

std::string reverse;
std::cin >> reverse;
std::reverse(reverse.begin(), reverse.end());
std::cout << "The string reversed is: " << reverse;

我在所有的项目中都定义了_CRT_SECURE_NO_WARNINGS来关闭这些警告。

由于标准strcpy可能导致缓冲区溢出和内存损坏,您可以使用strcpy_s代替。

您可以使用memcpy复制您的字符串。Strcpy可能在内部使用了memcpy