stringstream を再利用するには
C++ の STL の話。文字列を string に入れて istringstream のコンストラクタに文字列を与えると、そのインスタンスを標準入出力からの入力のようにストリームとして扱えます(というか元からそれが目的か)。
string buf;
getline(cin, buf);
istringstream iss(buf);
while( !iss.eof() ){
string s;
iss >> s;
cout << s << endl;
}
一行に複数の入力があるときはこれがとても便利。でも今までは、上の変数 iss は上のように使用したらそれっきり再利用できず、別の文字列を同様にストリームにしたいときは新しく istringstream 型の変数を用意してました。同じ変数に新しい文字列を与えてまた同じ変数を使いたいと常々思ってたんですが、どうやればいいのかさっぱり分からなかったので。
しかし最近解決策を知りました。 istringstream じゃなくて stringstream を使えばいいのだ…!
string strm("test exam end");
stringstream ss(strm);
string s;
while( !ss.eof() ){
ss >> s;
cout << s << endl;
}
ss.str( "" );
ss.clear();
cout << "cleared" << endl;
ss << strm;
while( !ss.eof() ){
ss >> s;
cout << s << endl;
}
ss.str( "" ); でストリーム中の文字列を消し、 ss.clear(); で eof 等の内部状態のフラグを初期化。 ss < < strm; で新しい文字列をストリームへ。上のコードだと空白区切りで文字列が出てくるので、次のように標準出力に出てきます。
test exam end cleared test exam end
なるほど、と思ったのでここにメモ。
About this entry
You’re currently reading “stringstream を再利用するには,” an entry on 数奇な因子
- Published:
- 木曜日, 7月 27th, 2006 at 13:02:46
- Author:
- line
- Category:
- programming
Comments are closed
Comments are currently closed on this entry.