C++ C++;从char*到char的转换无效(char*=*string.begin())

C++ C++;从char*到char的转换无效(char*=*string.begin()),c++,char,readfile,C++,Char,Readfile,我有以下代码: std::string extract() { fstream openfile("/home/name/Documents/testfile"); std::string teststring; long location = 4; long length = 2; teststring.resize(length); char* begin = *teststring.begin(); openfile.seekp(l

我有以下代码:

std::string extract() {

    fstream openfile("/home/name/Documents/testfile");
    std::string teststring;
    long location = 4;
    long length = 2;
    teststring.resize(length);
    char* begin = *teststring.begin();
    openfile.seekp(location);
    openfile.read(begin, length);

    return teststring;
}
这段代码应该返回在文件中找到的字符串。例如,如果文件的内容是

StackOverflow
此方法应返回

kO
这段代码是一位友好的StackOverflow用户提供给我的。我的问题是,我得到一个编译错误,它说:“从char*到char的转换无效”。问题在于

char* begin = *teststring.begin();

线路。如何修复此问题?

如果要将迭代器值转换为基础数据,有一个技巧可以获取指向第一个元素的指针

auto iterator_testdata = testdata.begin();
char* first_element_in_testdata = &(*iterator_testdata);
假设迭代器迭代字符值

这个技巧也适用于vector::begin()和类似的连续容器。小心使用

teststring.begin()返回一个迭代器,如果使用
*
运算符取消对它的引用,则会得到一个对字符的引用(
char&

因此,您可以将其地址设置为:

char* begin = &*teststring.begin();
或者你可以这样做:

char* begin = &teststring[0];

向量也是如此。在vector(C++11)中,添加了一个名为
data()
的新函数,该函数返回指向T的指针

所以用一个向量你就可以

char * begin = myvector.data(); // (if T is char)

左侧为
char*
,而右侧为
char
。只需从RHS中删除
*
。@Pavel Gatnar这会产生错误代码错误:无法将中的'std::basic\u string::iterator*{aka\uuuuu gnu\u cxx::uuuu normal\u iterator*}转换为'char*'initialization@bartgol字符串迭代器不是字符,你说得对。我真傻。Jose的回答是我应该写的:取消引用,然后获取地址。还有另一种方式:
&teststring.front()
更新,实际上不知道这个(似乎是C+11)。我已经习惯了另外两个。谢谢!它起作用了。我正在使用char*begin=&*teststring.begin();而且它工作得很漂亮
char * begin = myvector.data(); // (if T is char)