Convert char* to string C++

后端 未结 5 2024
轮回少年
轮回少年 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 04:14

    std::string str(buffer, buffer + length);
    

    Or, if the string already exists:

    str.assign(buffer, buffer + length);
    

    Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length characters, or until a null terminator, whichever comes first, then you can use this:

    std::string str(buffer, std::find(buffer, buffer + length, '\0'));
    

提交回复
热议问题