c++ - 我想使用 strcpy_s 将字符串转换为 char,但它给出了大小错误

标签 c++ string strcpy

我正在尝试使用 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/

相关文章:

C++在循环中插入更多 "\t"

java - java中高效的字符串匹配

c++ - 如何在字符串中查找格式化数字?

c++ - 存储 char 指针然后稍后填充它

c - 在 C 中连接两个字符串的安全方法

c++ - 消除 HTML 的最佳 C/C++ 库?

c++ - 取消引用已删除的指针总是会导致访问冲突?

c++ - 在 boost::any 映射中插入元素并返回对它的引用

python - 什么是从 python 字符串中删除空行的快速单行代码?

strcpy 中的 char * 和 char[]