我如何在std :: string中访问char数组?

问题描述 投票:1回答:1

我被赋予了在Linux中编写一个将存储设备模拟为文件的文件系统的任务。

我获得的功能之一需要读取“文件”中的数据。为此,我有一个应该返回std :: string的函数。

如何使用以下功能从文件中读取数据直接放入std :: string?

void read(int addr, int size, char *ans)

是否可以将std :: string内部的char数组作为参数传递给此函数?到目前为止,我遇到的所有方法和成员函数仅返回const char*,在这种情况下不起作用。

谢谢!

c++ arrays stdstring
1个回答
0
投票

常规方法是将指针传递给字符串的第一个字符。因为标准保证std::basic_string内的字符是连续存储的,所以可以保证此方法有效。

因此,

read(addr, str.size(), & str[0]);

作品。


-2
投票

实际上,这样做不是一个好主意,因为那时std::string类不知道插入了多少个字符。最好创建本地缓冲区std::array<char, 256> buf,将其传递给函数,然后使用std::string将其放入std::string(buf.data, buf.size())

© www.soinside.com 2019 - 2024. All rights reserved.