Dealing with char buffers

前端 未结 9 1548
情书的邮戳
情书的邮戳 2021-02-08 02:33

As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:

char buffer[512];
sprintf(buffer, \"Hello %s!\", userName.c_s         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 03:08

    If a function gives you a method of knowing how many characters it will return, use it. Your sample GetCurrentDirectory is a good example:

    DWORD length = ::GetCurrentDirectory(0, NULL);
    

    Then you can use a dynamically allocated array (either string or vector) to get the result:

    std::vector buffer(length, 0);
    // assert(buffer.capacity() >= length);  // should always be true
    GetCurrentDirectory(length, &buffer[0]);
    

提交回复
热议问题