6. I/O

input/output stream จาก fstream สามารถใช้เพื่อการเขียนอ่านไฟล์ โดยอาจใช้ตามตัวอย่างนี้

        #include <iostream>
        #include <fstream>
        using namespace std;

        int main(){
            //write file
            ofstream myfile1 ( "myfile.txt" );
                myfile1<<"Hello World!"<<endl;
                myfile1<<"Class cs112 is awesome!!"<<endl;
            myfile1.close();

            //read file
            ifstream myfile2 ( "myfile.txt" );
            for (string line; getline(myfile2, line); ){
                cout << line << endl;
            }
            myfile2.close();
            return 0;
        }

output

Running /home/ubuntu/workspace/code426_read_write_files.cpp                                               
Hello World!                                                                                              
Class cs112 is awesome!!

6.1 Output object

ถ้าเราต้องการใช้ operator << เพื่อส่งข้อมูลออก และสามารถใช้งานในรูปแบบ out<<"some"<<"text"; เราสามารถใช้โครงสร้างโปรแกรมต่อไปนี้ได้

    #include <iostream>
    using namespace std;
    class Out{
      public: 
      string s;
      Out(string _s=""){s=_s;}
      void show(){
        cout<<s<<endl;
      }
    };
    Out& operator<< (Out& out, string s2){
      out.s+=s2+" ";
      return out;
    }
    int main(){
      Out myout;
      myout<<"Hello"<<"my"<<"world!";
      myout.show();
      return 0;
    }

output

    Running /home/ubuntu/workspace/code426_class_Out.cpp                                                 
    Hello my world!

6.2 ostream

เราสามารถทำการ overloading เพื่อทำการส่งข้อมูลไปยัง ostream โดยใช้ operator "<<".

    #include<iostream>
    using namespace std;
    class Obj{
      private: 
        string s;
      public:
        Obj(){}// what will happend if we remove this line?
        Obj(string _s){
            s=_s;
        }
        friend ostream& operator<<(ostream& out, const Obj& A);
    };
    ostream& operator<<(ostream& out, const Obj& A) {
        return out<<" "<<A.s;
    }
    int main(){
        Obj A("Hello"), B("World!");
        cout<<A<<B;
        return 0;
    }

output

    Running /home/ubuntu/workspace/code601_ostream.cpp                                                   
     Hello World!

results matching ""

    No results matching ""