string.assign()とstring.copyのテストコード

char配列とstring文字列の相互やりとりは、以下のコードでなんとかなる

#include 
#include 
#include 
using namespace std;
int main() {
    char mosa[10];
    mosa[0]='a';
    mosa[1]='b';
    mosa[2]='';
    mosa[3]='c';
    mosa[4]=5;
    mosa[5]=6;
    string hoge;
    cout.write(mosa,6); // バイナリ出力
    cout <<endl;
//	hoge = mosa; // char文字列は代入するだけで、ヌル文字直前までコピーされる。
    hoge.assign(mosa, 6); // サイズを指定した、char配列のstring型への代入
    cout <<hoge.size() <<endl;
    cout <<hoge.c_str() << endl;
    cout <<hoge[3] <<endl;
    printf("%dn",hoge[4]);
    char bin[10];
    hoge.copy(bin,6); // サイズを指定した、stringデータのchar配列への代入
//    memcpy(bin,hoge.c_str(),6);
    printf("bin=%d",bin[5]);
    return 0;
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です