Home

Inserting with the << Operator in C++

|
Updated:  
2016-03-26 08:29:48
|
C++ For Dummies
Explore Book
Buy On Amazon

Writing to a file is easy in C++. You’re probably already familiar with how you can write to the console by using the cout object, like this:

cout << "Hey, I'm on TV!" << endl;

Well, guess what! The cout object is a file stream! Amazing! And so, if you want to write to a file, you can do it the same way you would with cout:. You just use the double-less-than symbol, called the insertion operator, like this:

If you open a file for writing by using the ofstream class, you can write to it by using the insertion operator. The FileWrite01 example shown demonstrates how to perform this task.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ofstream outfile("outfile.txt");
    outfile << "Lookit me! I'm in a file!" << endl;
    int x = 200;
    outfile << x << endl;
    outfile.close();
    return 0;
}

The first line inside the main() creates an instance of ofstream, passing to it the name of a file called outfile.txt.

You then write to the file, first giving it the string, Lookit me! I'm in a file!, then a newline, then the integer 200, and finally a newline. And after that, show the world what a good programmer you are by closing your file.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.