The C++ standard library provides type istream for input and type ostream for output.
Input <------------------------> Output
istream iostream ostream
keyboard screen
For example, cin is the standard input stream which is an object of istream and cout is the standard output steam which is an object of ostream.
int a=0;
cin>>a;
cout<<a;
We overloaded >> for Date type.
ostream & operator<<(ostream & os, const Date & d){
os<<d.month()<<"-"<<d.day()<<", "<<d.year();
return os;
}
//
Date d {2016,Month::feb,10};
cout<<d;
As you can see above, we work with os which is an object of ostream. cout corresponds to os here.
Files <-- I/O system --> Main memory
sequence Objects
of bytes of types
<- serialization(ORM)
deserialzation ---->
ifstream fstream ofstream
Read Write
For serialization, check https://en.wikipedia.org/wiki/Serialization
Reading
Writing
Read.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
//
cout << "File name:";
string name;
cin >> name;
ifstream myfile {name}; //Read
vector<double> data;
if(myfile){
for(double x;myfile>>x;){
data.push_back(x);
}
}
else cerr<<"Can't open "<<name;
Write
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
//
cout << "File name:";
string name;
cin >> name;
ofstream myfile {name};// open or create to write.
vector<double> data={1,2,3,4};
if(myfile){
for(double x : data ){
myfile<<x<<endl;//Write
}
}
else cerr<<"Can't open "<<name;
To stop typing, just type an enter.
for(string user="";;){
getline(cin, user);// We need to use a getline to handle an enter.
if (user.length() == 0) break;
else users.push_back(user);
}