(Suggested book reading: Programming Abstractions in C++, Chapters 3-4)
Today we will learn about the C++ stream objects that perform input and output (called "I/O") from the console or files. Here is an example of using a stream to read a file and print its contents:
#include <fstream>
#include <iostream>
#include <string>
#include "console.h"
using namespace std;
int main() {
// read and print every line of a file
ifstream input;
input.open("poem.txt");
string line;
while (getline(input, line)) {
cout << line << endl;
}
input.close();
return 0;
}
This code uses two different stream objects:
input
is an input file stream, or ifstream
.
cout
, which does console output.