Examples C++

Write Strings to a File

In this C++ example, we demonstrate how to write a series of strings to a file. First, we create an output file object, which has the class type ofstream; The o stands for output, the f stands for file, and stream means that it accepts streams of data. In this case, the stream is a set of characters.

After we create the stream objeect, we open the file for writing. In general, streams can be opened for reading, writing, or both. Output streams are opened for writing by default. Finally, we write the four cardinal virtues to the file and close it.

And if any one loves righteousness, her labors are virtues; for she teaches self-control and prudence, justice and courage; nothing in life is more profitable for men than these. (Wisdom 8:7)

Virtues.txt

Fortitude
Prudence
Justice
Temperance
 

main.cpp

#include <iostream>
#include <fstream>

int main() {
  std::cout << "Writing to the file . . ." << std::endl;

  // We will create an output file stream so that we can open it for writing.
  std::ofstream qTextFile;
  // Create a new file or write over an old one.
  qTextFile.open("Virtues.txt");
  // Write the four cardinal virtues to it.
  qTextFile << "Fortitude" << std::endl;
  qTextFile << "Prudence" << std::endl;
  qTextFile << "Justice" << std::endl;
  qTextFile << "Temperance" << std::endl;
  qTextFile.close();
  return 0;
}
 

Output

Writing to the file . . .
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.