0

I'm trying to copy a string to buffer for further processing. I used the instruction

char *buf = line.c_str();

but buf type should be const char*, However If I'm going to use

const char *buf = line.c_str();

I'll face another problem as I'm using strtok_s function for processing the buf. this function expecting char * arg. rather than const char*. Is there another function or a way to copy this line to char * ??

4

2 回答 2

1

Try this.

char* buf = strdup(line.c_str());
// use strtok_s however you need
free(buf);

You can't use the buffer directly without modifying it because strtok_s does actually modify the data. c_str wants you to leave the data alone.

If you don't care about the modifications, just do:

char* buf = &line[0];
于 2013-06-02T04:00:00.207 回答
1

One approach is to use standard library containers, such as std::vector or C++14's std::dynarray:

std::vector<char> v(line.begin(), line.end());

Bear in mind that this copies line's characters without the null termination \0. In this sense, the buffer does not represent a string. If you need null termination (which is not clear from the question), you have to add it manually:

v.push_back('\0');

Then you can use the underlying data via

char* c1 = &v[0]
char* c2 = v.data(); // c++11
于 2013-06-02T06:52:06.167 回答