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

前端 未结 11 973
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:35

    char mystring[101]; // a 100 character string plus terminator
    char *any_input;
    any_input = "Example";
    iterate = 0;
    while ( any_input[iterate] != '\0' && iterate < 100) {
        mystring[iterate] = any_input[iterate];
        iterate++;
    }
    mystring[iterate] = '\0';
    

    This is the basic efficient design.

提交回复
热议问题