4.input Output Library
4.input Output Library
Input/Output Library
Phenikaa University
Stream Concept
String Streams
Definition
stream
▶ Sequence of bytes flowing in and out of the programs
▶ Think of streams as a pipeline of data (just like water and oil flowing through a
pipe).
▶ Streams acts as an interface between the programs and the actual IO devices
▶ Streams convert between data and the string representation of data.
Two ways to classify streams
An output stream lets you take data from your program and output it to a source (like
the console, a file, etc.).
▶ Can only send data to the stream.
▶ Send data using stream insertion operator: <<
▶ Converts data into string and sends to the stream.
The std::cout stream is an example of an output stream.
std::cout << 5 << std::endl;
// converts int value 5 to string ’5’
// sends ’5’ to the console output stream
Input Streams
An input stream lets you get data from a source (like user input, a file, a webpage,
etc.) and read it in your program.
▶ Can only receive data.
▶ Pull out data using stream extraction operator: >>
▶ Extraction receives data from stream as a string and converts it into the
appropriate type.
The std::cin stream is an example of an input stream.
int x;
string str;
std::cin >> x >> str;
//reads exactly one int then one string from console
I/O Decision Tree
Outline
Stream Concept
String Streams
Outline
Stream Concept
String Streams
Reading in a File
inFile.open("Lecture4");
if (inFile.fail())
{
cout << "Unable to open file!\n";
exit(0);
}
...
Step 2: Read the file - One word at a time
Stream Concept
String Streams
Step 1: Open the file
Before we can use an output stream in a program, we must create stream object:
ofstream outFile;
To connect the ofstream outFile to the file ”result.txt”, we use the following
statement:
outFile.open("result.txt");
Step 2+3: Write the file, then close
int main(){
...
outFile << "List of numbers: ";
for (int num : vec)
outFile << num << " ";
outFile << "\n";
outFile << "Sum = " << total << endl;
outFile.close();
That Looks Familiar...
▶ If file-writing syntax seems similar to printing to the console, that’s because it is!
- cin is an ifstream; cout is an ofstream
Here’s the problem
or this ...
getline() and stringstreams
Stream Concept
String Streams
stringstream