这是正确的还是有更好的方法。
Visual Studio 给出错误提示“strcpy() is depreciated”。
using namespace std;
char* ptr;
ptr=(char *)calloc(1,sizeof(char));
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
ptr = (char *)realloc(ptr, top + eqn.size()+1);
strcpy(ptr, eqn.c_str());
附言我希望 ptr 成为输入方程式的确切大小。
最佳答案
假设您要实现的目标是创建一个 modifiable
给定 std::string
的字符缓冲区, 更好的选择是使用 std::vector<char>
创建这样一个缓冲区。
#include <vector>
#include <string>
#include <iostream>
//...
void foo(char *x)
{
// do something to 'x'
}
using namespace std;
int main()
{
cout << "Input the equation." << endl;
string eqn;
getline(cin, eqn);
// construct vector with string
std::vector<char> ptr(eqn.begin(), eqn.end());
// add null terminator
ptr.push_back(0);
foo( &ptr[0] );
}
上面的代码利用 std::vector
创建了一个可修改的、以 null 结尾的 C 字符串。称为 ptr
.请注意,没有调用 malloc
, calloc
等
关于c++ - 在C++中将字符串输入到动态分配的char内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825076/