How to copy a string into a char array in C++ without going over the buffer

前端 未结 11 980
Happy的楠姐
Happy的楠姐 2020-12-08 03:13

I want to copy a string into a char array, and not overrun the buffer.

So if I have a char array of size 5, then I want to copy a maximum of 5 bytes from a string in

11条回答
  •  忘掉有多难
    2020-12-08 03:30

    This is exactly what std::string's copy function does.

    #include 
    #include 
    
    int main()
    {
    
        char test[5];
        std::string str( "Hello, world" );
    
        str.copy(test, 5);
    
        std::cout.write(test, 5);
        std::cout.put('\n');
    
        return 0;
    }
    

    If you need null termination you should do something like this:

    str.copy(test, 4);
    test[4] = '\0';
    

提交回复
热议问题