Visualization Tool Kit(VTK)など

PrintMatrixの改良

PrintMatrixは内部でcout(console out)を使っています.そのため,標準出力にしか出力できません.
しかし,出力対象を画面に限定する理由はなく,ファイル,プリンタ,Windowsのコントロール(エディットボックスなど)など対象はたくさんあります.

そこで,文字列化して取り出すという機能を実装します.

文字列

C言語では文字列という型はありませんので,char(文字)の配列を使います.
そのため,常にポインタで扱う必要がありました.

C++では標準ライブラリにstd::stringという文字列クラスがあります.
例えば+演算子で結合したり,std::string::size()で文字数を手に入れたり,std::string::substr()で部分文字列を手に入れたりできます.

文字列の整形

Cではsprintfという関数でprintfの書式で文字列を整形することができます.

char str[100];
sprintf(str, "%f, %f\n%f, %f\n", mat[0], mat[1], mat[2], mat[3]);

C++ではostringstreamというcoutと同じ文法で整形することができます(もちろんsprintfも使えますが).

// #include <sstream>が必要
std::ostringstream oss;
oss << mat[0] << ", " << mat[1] << std::endl << mat[2] << ", " << mat[3] << std::endl;
std::string str = oss.str();

Matrix2x2::PrintMatrixの改良

では,stringとostringstreamを使って改良しましょう.

#include <sstream>
class Matrix2x2
{
public:
  std::string GetPrintString() const;
};

std::string Matrix2x2::GetPrintString() const
{
  std::ostringstream oss;
  oss << mat[0] << ", " << mat[1] << std::endl;
  oss << mat[2] << ", " << mat[3] << std::endl;
  oss << std::endl;
  return oss.str();
}

#include <fstream>
int main()
{
  Matrix2x2 mat(1.0, 2.0, 3.0, 4.0);
  std::cout << mat.GetPrintString() << std::endl;

  std::ofstream ofs("test.txt"); // ファイルへの出力
  ofs << mat.GetPrintString() << std::endl;
}

例のように,coutはstringを受け付けるのでcoutに直接与えることができます.
同様にファイル出力クラスfstreamを使えばファイルに全く同じ物を書き込めます.
汎用性が高くなりました.

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu

メニュー

チュートリアル

アルゴリズム(数学)

並列計算

STL

#include<memory> #include<string> #include<sstream> #include<algorithm> #include<functional> #include<numeric>

Media Foundation

【メニュー編集】
Wiki記法ガイド

メンバーのみ編集できます