c_str()

c_str()はstringオブジェクトをC言語形式の文字列に変換します。

c_str()の書式は次のとおりです。


  #include <string>
  const E *basic_string::c_str() const;
  

変換された文字列は定数であるので、そのままでは変更できません。変更したいときには、別のバッファに保存してから変更する必要があります。

次の例は、C言語の関数を使うためにstringオブジェクトをC言語形式の文字列に変換するプログラムの例です。


    #include <iostream>
    #include <string>
    #include <string.h>
    #ifdef _MSC_VER
    #pragma warning(disable : 4996)
    #pragma warning(disable : 6053)
    #endif
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
      string s = "01234567";
    
      char buff[128];
      // C言語形式の文字列バッファに保存する
      strcpy(buff, s.c_str());
    
      // 文字列を追加する
      strcat(buff, " and ABC");
    
      string d = string(buff);
      // 標準出力に出力する
      cout << d << endl;
    
      return 0;
    }
  

実行結果は次のようになります。


    01234567 and ABC
  

関連項目

deque


  


C++目次 inserted by FC2 system