将std字符串转换为const char*

Vis*_*hal 1 c++ file-io

我运行这段代码时遇到错误

  string line;
  getline (myfile,line);
  char file_input[15];
  strncpy(file_input, line, 6);
  cout << line << endl;
Run Code Online (Sandbox Code Playgroud)

错误 - 无法将'std :: string'转换为'const char*'以将参数'2'转换为'char*strncpy(char*,const char*,size_t)'如何摆脱这个?

San*_*ker 5

试试:

strncpy(file_input, line.c_str(), 6);
Run Code Online (Sandbox Code Playgroud)

这使用了c_str()std::string类型的成员函数.