[英]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?错误 - 无法将参数 '2' 的 'std::string' 转换为 'const char*' 到 'char* strncpy(char*, const char*, size_t)' 如何摆脱这个?
strncpy(file_input, line.c_str(), 6);
But why would you want the fixed-length buffer file_input
in the first place?但是为什么你首先想要固定长度的缓冲区file_input
呢? It would be safer to construct it as a new std::string
containing the first five characters in line
:将其构造为包含line
前五个字符的新std::string
会更安全:
std::string file_input(line, 0, 5);
Converting from c++ std string to C style string is really easy now.从 c++ 标准字符串转换为 C 样式字符串现在非常容易。
For that we have string::copy
function which will easily convert std string to C style string.为此,我们有string::copy
function 可以轻松地将 std 字符串转换为 C 样式字符串。 reference参考
string::copy
functions parameters serially string::copy
函数参数
Another important thing,还有一点很重要,
This function does not append a null character at the end of operation.这个 function 在操作结束时不会 append 一个 null 字符。 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;
Vice Versa, Converting from C style string to C++ std string is lot more easier反之亦然,从 C 样式字符串转换为 C++ 标准字符串要容易得多
There is three ways we can convert from C style string to C++ std string我们可以通过三种方式将 C 样式字符串转换为 C++ 标准字符串
First one is using constructor,第一个是使用构造函数,
char chText[20] = "I am a Programmer";
// using constructor
string text(chText);
Second one is using string::assign
method第二个是使用string::assign
方法
// char string
char chText[20] = "I am a Programmer";
// c++ string
string text;
// convertion from char string to c++ string
// using assign function
text.assign(chText);
Third one is assignment operator(=), in which string class uses operator overloading第三个是赋值运算符(=),其中字符串 class 使用运算符重载
// char string
char chText[20] = "I am a Programmer";
// c++ string
// convertion from char string to c++ string using assignment operator overloading
string text = chText;
third one can be also write like below -第三个也可以像下面这样写 -
// char string
char chText[20] = "I am a Programmer";
// c++ string
string text;
// convertion from char string to c++ string
text = chText;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.