Visual studio doesn't support strcpy_s function in C

177 Views Asked by At

I'm new to C++ and currently using Visual Studio for coding. My strcpy_s() does not work for some reason

#include<iostream>
#include<cstring>

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

This programme should print "Hello C++", however it does not.

I tried other editors (including online C++ IDE) and this issue is fixed. Is there a way to fix this problem in Visual Studio?

Thank you!

1

There are 1 best solutions below

0
Minxin Yu - MSFT On

strcpy_s requires dest_size. The behavior of strcpy_s is undefined if the source and destination strings overlap.

#include<iostream>

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

Possible output: Hello C++

Another solution:

#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;
}