我正在尝试使用 strcpy_s,但我在处理大小时遇到另一个错误,说:L "Buffer is too small && 0"
当我尝试运行该程序时,我没有知道 strcpy_s(tochar, sizeof tochar, test.c_str());
中的 sizeof tochar
是否正确,因为我不断收到此错误。
完整编译代码:
#include "stdafx.h"
#include <string>
#include <string.h>
#include <cstring>
#include <stdlib.h>
#include <errno.h>
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
using std::vector;
using std::string;
int main()
{
std::string test;
std::vector<std::string> v3 = { "filename1", "filename2","filename3", };
for (int m = 0; m < v3.size(); m++) {
test = "\"" + v3[m] + ".txt" + "\"";
char * tochar = new char[test.length() + 1];
strcpy_s(tochar, sizeof tochar, test.c_str());
std::cout << tochar << std::endl;
}
return 0;
}
我不能在 C++ 2015 中使用 strcpy
,我现在必须使用 strcpy_s
因为 strcpy
给出了不同的错误,我不想只是关闭错误。 (除非我可以在程序中放入某种代码,让它用 strcpy
编译)
我希望 tochar
输出:"filename1.txt"
最佳答案
strcpy_s 的第二个拷贝应该是您要复制的字符数。
strcpy_s(tochar, test.length() + 1, test.c_str());
我认为这是一种写法。
sizeof tochar
给你的是 char 指针变量的大小,而不是你分配的数组的大小。
关于c++ - 我想使用 strcpy_s 将字符串转换为 char,但它给出了大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32928750/