c++中strcpy的替代品
alternative for strcpy in C++
嘿,我是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
相关文章:
- 使用strcpy将char数组的元素复制到另一个数组
- C++中原子的替代品<variant>
- strcpy 在类中无法使用字符串指针
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- C++sscanf_s的替代品
- C++ strcpy 函数在少数主要情况下失败
- 在函数 strcpy() 中访问字符数组时出现分段错误
- getline的替代品
- 什么是 std::function::argument_type 的替代品?
- C++编译 strlen 和 strcpy 的问题
- 堆栈数组c++的Strcpy行为
- 有DirectShow的替代品吗?
- 无法使用 strcpy 将字符串复制到静态结构成员
- 智能指针作为 QObject::d eleteLater() 的替代品
- C++中 mktime 的替代品
- 对于C++,是否有任何现代的 std::strchr() 替代品?
- 澄清了 strcpy() 在像这样初始化字符数组时的工作 *Arr.
- shared_future是<void>condition_variable的合法替代品吗?
- C++ 从文件中获取数据时使用 strcpy 和 strcmp 按字母顺序对数组进行排序?
- c++中strcpy的替代品