开发者

Converting std string to const char*

I am getting开发者_如何学C an error when I run this piece of code

  string line;
  getline (myfile,line);
  char file_input[15];
  strncpy(file_input, line, 6);
  cout << line << endl;

Error - cannot convert ‘std::string’ to ‘const char*’ for argument ‘2’ to ‘char* strncpy(char*, const char*, size_t)’ How to get rid of this?


Try :

strncpy(file_input, line.c_str(), 6);

This uses the c_str() member function of the std::string type.


strncpy(file_input, line.c_str(), 6);

But why would you want the fixed-length buffer file_input in the first place? It would be safer to construct it as a new std::string containing the first five characters in line:

std::string file_input(line, 0, 5);


Converting from c++ std string to C style string is really easy now.

For that we have string::copy function which will easily convert std string to C style string. reference

string::copy functions parameters serially

  1. char string pointer
  2. string size, how many characters will b copied
  3. position, from where character copy will start

Another important thing,

This function does not append a null character at the end of operation. So, we need to put it manually.

Code exam are in below -

// char string
char chText[20];

// c++ string
string text =  "I am a Programmer";

// conversion from c++ string to char string
// this function does not append a null character at the end of operation
text.copy(chText, text.size(), 0);

// we need to put it manually
chText[text.size()] = '\0';

// below statement prints "I am a Programmer"
cout << chText << endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜