Bri*_*own 89 c++ string type-conversion
我想转换string为char数组但不是char*.我知道如何将字符串转换为char*(通过使用malloc或我在代码中发布它的方式) - 但这不是我想要的.我只是想转换string为char[size]数组.可能吗?
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
// char to string
char tab[4];
tab[0] = 'c';
tab[1] = 'a';
tab[2] = 't';
tab[3] = '\0';
string tmp(tab);
cout << tmp << "\n";
// string to char* - but thats not what I want
char *c = const_cast<char*>(tmp.c_str());
cout << c << "\n";
//string to char
char tab2[1024];
// ?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Cho*_*ett 113
我能想到的最简单的方法是:
string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());
Run Code Online (Sandbox Code Playgroud)
为安全起见,您可能更喜欢:
string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
Run Code Online (Sandbox Code Playgroud)
或者可以这种方式:
string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());
Run Code Online (Sandbox Code Playgroud)
小智 52
好吧,我感到震惊的是,现在轮到我了,没有人真正给出了一个好的答案.有两种情况;
一个常量字符数组对你来说足够好,所以你去,
const char *array = tmp.c_str();
Run Code Online (Sandbox Code Playgroud)或者您需要修改 char数组,因此常量不正常,然后再使用它
char *array = &tmp[0];
Run Code Online (Sandbox Code Playgroud)它们都只是作业操作,大部分时间都是你需要的,如果你真的需要一个新的副本,那么请跟随其他研究员的答案.
小智 16
最简单的方法是做到这一点
std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
Run Code Online (Sandbox Code Playgroud)
You*_*uka 10
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0'; // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0'; // before C++11 (safe)
Run Code Online (Sandbox Code Playgroud)
在C++中避免使用C是一种更好的做法,因此应该选择std :: string :: copy而不是strcpy.
小智 5
尝试这种方式应该是有效的.
string line="hello world";
char * data = new char[line.size() + 1];
copy(line.begin(), line.end(), data);
data[line.size()] = '\0';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
504904 次 |
| 最近记录: |