cに「helloworld」を入れる必要があります。これどうやってするの ?
string a = "hello ";
const char *b = "world";
const char *C;
string a = "hello ";
const char *b = "world";
a += b;
const char *C = a.c_str();
または変更せずにa
:
string a = "hello ";
const char *b = "world";
string c = a + b;
const char *C = c.c_str();
111111によって与えられた情報の量に一致するように少し編集します。
すでにstring
s(またはconst char *
sがありますが、後者を前者にキャストすることをお勧めします)がある場合は、それらを「合計」して、より長い文字列を形成できます。ただし、既存の文字列以外のものを追加する場合は、を使用できます。これは、stringstream
とoperator<<
まったく同じように機能cout
しますが、テキストを標準出力(つまり、コンソール)に出力するのではなく、内部バッファーに出力します。そして、あなたはそれ.str()
から得るためにそれの方法を使うことができますstd::string
。
std::string::c_str()
const char
関数は、その中に含まれている文字列のバッファ(つまり)へのポインタを返しますconst char *
。これはnullで終了します。const char *
その後、他の変数として使用できます。
連結する必要がある場合は、operator +
andoperator +=
関数を使用します
#include <string>
///...
std::string str="foo";
std::string str2=str+" bar";
str+="bar";
ただし、実行する連結が多い場合は、文字列ストリームを使用できます
#include <sstream>
//...
std::string str1="hello";
std::stringstream ss;
ss << str1 << "foo" << ' ' << "bar" << 1234;
std::string str=ss.str();
const char *
編集:次に、文字列をC関数に渡すことができますc_str()
。
my_c_func(str1.c_str());
Cfuncが非constchar*を取得する場合、または所有権が必要な場合は、次のように実行できます。
char *cp=std::malloc(str1.size()+1);
std::copy(str1.begin(), str2.end(), cp);
cp[str1.size()]='\0';