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

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

#include <string>
#include <iostream>

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';

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)