C ++ Incorrect conversion from char * to char (char * = * string.begin ())

I have the following code:

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;
}

This code should return a string of characters found in the file. For example, if the contents of a file

StackOverflow

this method should return

kO

This code was provided to me by a friendly user of StackOverflow. My problem is that I get a compilation error that reads: "Invalid conversion from char * to char". The problem is

char* begin = *teststring.begin();

lines. How can i fix this?

+4
source share
2 answers

teststring.begin () returns an iterator, and if you search for it using the operator *, you will get a link to char ( char&).

:

char* begin = &*teststring.begin();

:

char* begin = &teststring[0];

char* begin = &teststring.front() //(C++11) [@Jonathan Wakely]

. Altho (++ 11) ​​ data(), T;

,

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

, , .

auto iterator_testdata = testdata.begin();
char* first_element_in_testdata = &(*iterator_testdata);

char.

vector:: begin() . .

+1

Source: https://habr.com/ru/post/1628015/


All Articles