Vishal
Vishal

Reputation: 999

Converting std string to const char*

I am getting 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?

Upvotes: 2

Views: 3640

Answers (3)

SHAH MD IMRAN HOSSAIN
SHAH MD IMRAN HOSSAIN

Reputation: 2889

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;

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363567

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

Upvotes: 3

Sander De Dycker
Sander De Dycker

Reputation: 16243

Try :

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

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

Upvotes: 5

Related Questions