c++ Visual Studio不支持C中的strcpy_s函数

oyxsuwqo  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(122)

我是C++新手,目前使用Visual Studio进行编码。我的strcpy_s()由于某种原因无法工作

#include<iostream>
#include<cstring>

int main(){
    char a[]="Hello World!";
    strcpy_s(a+6,"C++");
    std::cout<<a;
}

字符串
这个程序应该打印“Hello C++",但它没有。
我尝试了其他编辑器(包括在线C++ IDE),这个问题得到了解决。有没有办法在Visual Studio中解决这个问题?
谢谢你,谢谢

6tr1vspr

6tr1vspr1#

strcpy_s需要dest_size。如果源字符串和目标字符串重叠,则strcpy_s的行为未定义。

#include<iostream>

int main() {
    char a[] = "Hello World!";  
    strcpy_s(a + 6, strlen("C++")+1, "C++");
    std::cout << a;
}

字符串
可能的输出:Hello C++
另一个解决方案是:

#include<iostream>

int main() {
    char a[] = "Hello World!";  
    char b[20];
    strncpy_s(b, sizeof(b), a, 6);
    strcat_s(b, sizeof(b), "C++");
    std::cout << b;
}

相关问题