Streams: Classes and Errors| OOP in C++


Streams And Files


Stream


A stream is a sequence of bytes, it acts as a source or destination for data.
stream


Stream Classes for Console I/O Operations
streams


Overloaded operators >>and<<
The objects cin and cout are predefined in iostream file. The operator >> is overloaded in the istream class and << is overloaded in the ostream class. This is the reason, how, the same operator can handle various data types(e.g int, float, char. etc).
Put() and get() functions
get() has two variants, get(char *) and get(void), the get(char *) assigns the input to its argument and get(void) returns the input character
char c;
cin.get(c);
cout.put(c);
c=cin.get();
cout.put(c);
getline() and write() function
getline() can read a complete line(with white spaces). getline() can continuously read the characters in a line until the enter key is hit.
Syntax
cin.getline(line, SIZE)
e.g.
char name[20]
cout<<"\n Enter name";
cin.getline(name, 20);
cout.write(name, 20);
write() function can display entire line.
Syntax
cout.write(line, SIZE);


Formatted Console I/O Operations
IOS class contains many member functions that would help in formatting output. The file iomanip also includes many formatting functions.
Examples
Cout.width(5);
Cout<<512;
Output :
console i/o


cout.precision(3);
cout<<sqrt(2); cout<<"\n";
cout<<2.50032;
Output:
1.141
2.5


cout.fill('*');
cout.width(10);
cout<<512;
Output:

console i/o stream


self()
setf is a member of ios class and is used to change/specify formatting.
Syntax
cout.self(arg1, arg2)
where,
arg1 is flag
and arg2 is bit-field.
flag
Example:
cout.fill('*');
cout.setf(ios::left,IOS::adjustfield);
cout.width(15);
cout<<"INDIA 1";

Output:
stream classes


cout.fill('*');
cout.precision(3);
cout.setf(ios::internal, ios::adjustfield);
cout.setf(ios::scientific, ios::float field);
cout.width(15);
cout<<-12.34567;
program stream

Custom Search

%d bloggers like this: