Convert char* to string C++

后端 未结 5 1965
轮回少年
轮回少年 2021-01-31 03:29

I know the starting address of the string(e.g., char* buf) and the max length int l; of the string(i.e., total number of characters is less than or equ

5条回答
  •  清酒与你
    2021-01-31 03:57

    There seems to be a few details left out of your explanation, but I will do my best...

    If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

    string retrieveString( char* buf, int max ) {
    
        size_t len = 0;
        while( (len < max) && (buf[ len ] != '\0') ) {
            len++;
        }
    
        return string( buf, len );
    
    }
    

    If the above is not the case, I'm not sure how you determine where a string ends.

提交回复
热议问题