Monday, October 19, 2015

c++ i/o stream

c++ i/o stream

In order to use data in disk, monitor, keybord and other input/output devices, we need to use stream.
















We can think the stream as a bridge that connect your c++ program with oother input device.
For example, I am going to demonstrate your " cout " command.

cout << "hello world" ;

your c++ program runs " cout " --> stream is created --> your c++ programs grabs "hello world" --> "hello world" is sent to monitor via stream --> "hello world" is displayed on your monitor.

files and other input/output devices have same behaviour

I am going to show you how I can read and write text file using ifstream and ofstream.
ifstream = reading from a file
ofstream = writing to a file
---------------------------------------------------------------------------------------------------------------------------

 The following is practice code. If you have suggestion or correction, please feel free to leave comment.


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

int main() {
    //writing sth to " test.txt " file
    ofstream f;
    f.open("test.txt");
    f << "hello world" << endl;
    f.close();

    //read " text2.txt " file line by line
    ifstream ff ("text2.txt");
   
    //check whether text2.txt is usable file
    if( ff.is_open())
    {
         string line;

         //getline returns true until there is sth to read in the file
         //reading line is stored in string variable
         while ( getline( ff, line ))
        {
                cout << line << endl;
        }
    }

    ff.close()


}


No comments:

Post a Comment