如何复制包含“"字符的数据

2022-01-12 00:00:00 char c++ strcpy

我正在尝试复制包含"的数据.我正在使用 C++ .当研究结果是否定的时,我决定编写自己的函数来将数据从一个 char* 复制到另一个 char*.但它不会返回想要的结果!我的尝试如下:

I'm trying to copy data that conatin ''. I'm using C++ . When the result of the research was negative, I decide to write my own fonction to copy data from one char* to another char*. But it doesn't return the wanted result ! My attempt is the following :

#include <iostream>


char* my_strcpy( char* arr_out,  char* arr_in, int bloc )
{
 char* pc= arr_out;

 for(size_t i=0;i<bloc;++i)     
 {

        *arr_out++ = *arr_in++ ;
 }

 *arr_out = '';
 return pc;
}

int main()
{
    char * out= new char[20];
    my_strcpy(out,"12345aaaaaaa  AA",20);
    std::cout<<"output data: "<< out << std::endl;
    std::cout<< "the length of my output data: " << strlen(out)<<std::endl;
    system("pause");
    return 0;
}

结果在这里:

我不明白我的代码有什么问题.

I don't understand what is wrong with my code.

提前感谢您的帮助.

推荐答案

当您将 char* 写入 coutmy_strcpy 工作正常code> 或计算它的长度 strlen 他们 停止在 根据 C 字符串的行为.顺便说一句,你可以使用 memcpy 复制一个 char 块,而不管 .

Your my_strcpy is working fine, when you write a char* to cout or calc it's length with strlen they stop at as per C string behaviour. By the way, you can use memcpy to copy a block of char regardless of .

相关文章