Creating a Basic Text Editor Program in C++
In this tutorial, we will learn how to create a simple text editor using the C++ programming language. This text editor will allow the user to input, save, and display text using basic file operations.
Objective:
The objective of this project is to demonstrate how C++ can be used to create a basic text editor that can read and write text to a file. We will cover how to use file handling functions like ofstream and ifstream to manage files and process user input.
Code:
#include
#include
#include
using namespace std;
void displayMenu() {
cout << "Simple Text Editor" << endl;
cout << "1. Write Text" << endl;
cout << "2. Read Text" << endl;
cout << "3. Exit" << endl;
}
void writeTextToFile() {
string text;
ofstream outFile("editor.txt");
cout << "Enter text to save to file (Type 'exit' to stop):" << endl;
while (true) {
getline(cin, text);
if (text == "exit") break;
outFile << text << endl;
}
outFile.close();
cout << "Text saved to editor.txt" << endl;
}
void readTextFromFile() {
string line;
ifstream inFile("editor.txt");
if (inFile.is_open()) {
cout << "Text from file:" << endl;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Unable to open file!" << endl;
}
}
int main() {
int choice;
while (true) {
displayMenu();
cout << "Enter your choice: "; cin >> choice;
cin.ignore(); // to clear the input buffer after reading choice
switch (choice) {
case 1:
writeTextToFile();
break;
case 2:
readTextFromFile();
break;
case 3:
cout << "Exiting Text Editor." << endl;
return 0;
default:
cout << "Invalid choice! Please choose again." << endl;
}
}
return 0;
}
Program Explanation:
This program implements a simple text editor in C++ that allows the user to perform three tasks:
- Write Text: The user can input text, and it will be saved to a file named
editor.txt. - Read Text: The user can view the contents of the
editor.txtfile. - Exit: The program will terminate.
The program uses file handling features of C++ such as ofstream (output file stream) to write to a file, and ifstream (input file stream) to read from the file. It also uses simple getline() function to capture multi-line user input.
How to Run the Program:
- Open your C++ IDE or text editor.
- Copy and paste the code provided above into a new file.
- Save the file with a
.cppextension (for example,TextEditor.cpp). - Compile the program using your IDE or the command line.
- Run the compiled program.
- You can choose to write or read from the file based on the displayed menu.

