Stream - C++
C++の勉強
クラスFirstを作成して、そのオブジェクトを直接ストリームの演算子"<<"と">>"で操作?できるようにする。
mainの中のis >> test;がひとつだけだと、"Good Morning"のうち"Good"しか取得できないのがわからない。たぶんスペースで区切られるのだろうなぁと思ってis >> test >> test; としたら実行時にエラーになった。
単純な文字列の受け渡しなんかにはストリームは使用しないのだろうなと思いつつ。。。
test.h
#include <iostream> #include <string> using namespace std; class First { string str; public: First(); void set(const string s); void append(const string s); string get() const; }; ostream& operator<<(ostream& s, const First& x); istream& operator>>(istream& s, First& x);
test.cpp
#include <iostream> #include <sstream> #include "test.h" using namespace std; First::First() { str = "Hello"; } void First::set(const string s) { str = s; } void First::append(const string s) { if(str != "") str += " "; str += s; } string First::get() const { return str; } ostream& operator<<(ostream& str, const First& x) { return str << x.get(); } istream& operator>>(istream& is, First& x) { string s; is >> s; // cout << "s = " << s << endl; x.append(s); } int main() { First test; cout << test.get() << endl; cout << test << endl; string s = "Good Morning"; test.set(s); cout << test << endl; test.set(""); istringstream is(s); is >> test; // この行だけだと"Good"しか表示しない is >> test; cout << test << endl; return 0; }