How to convert a string literal to unsigned char array in visual c++

后端 未结 8 1491
闹比i
闹比i 2020-12-06 06:02

How to convert a string to Unsigned char in c++...

I have,

unsigned char m_Test[8];

I want to assign a string \"Hello world\"

相关标签:
8条回答
  • 2020-12-06 06:36

    You can use strcpy:

    unsigned char m_Test[8];
    strcpy((char*)m_Test, "Hello world");
    

    Note that "Hello world" is too long for 8 bytes, so you will probably get a segfault.

    0 讨论(0)
  • 2020-12-06 06:38

    Firstly, the array has to be at least big enough to hold the string:

     unsigned char m_Test[20];
    

    then you use strcpy. You need to cast the first parameter to avoid a warning:

     strcpy( (char*) m_Test, "Hello World" );
    

    Or if you want to be a C++ purist:

     strcpy( static_cast <char*>( m_Test ), "Hello World" );
    

    If you want to initialise the string rather than assign it, you could also say:

     unsigned char m_Test[20] = "Hello World";
    
    0 讨论(0)
  • 2020-12-06 06:38

    You can use a string copy function like strcpy or even better strncpy, which has also some size checks:

    strncpy ((char*) m_Test,"Hello World",8);
    
    0 讨论(0)
  • 2020-12-06 06:39

    You can use c_str() function of std::string to get the char* out of string. This method basically returns a pointer to c-style string. After this you can use the normal string copying functions such as strcpy or strncpy to copy the value in to test.

    0 讨论(0)
  • 2020-12-06 06:40

    you can use strcpy function But have in mind that m_Test is only 8 size and there will be an overflow. Strcpy won't check that and you will get an exception

    char * strcpy ( char * destination, const char * source );
    
    0 讨论(0)
  • 2020-12-06 06:49
    strncpy(m_Test, "Hello world", sizeof(m_Test));
    

    Here's Wikipedia on strncpy:

    0 讨论(0)
提交回复
热议问题