Text Editor in C++
Below is a basic example of a text editor using ofstream
and ifstream
for file operations in C++. Copy and paste this code into a C++ file (e.g., TextEditor.cpp) and run it.
// Include iostream, fstream and string #include class TextEditor { private: std::string filename; public: TextEditor(const std::string& file) : filename(file) {} void openFile() { std::ifstream inputFile(filename); if (inputFile.is_open()) { std::string line; while (getline(inputFile, line)) { std::cout << line << std::endl; } inputFile.close(); } else { std::cout << "Unable to open the file." << std::endl; } } void saveFile(const std::string& content) { std::ofstream outputFile(filename); if (outputFile.is_open()) { outputFile << content; outputFile.close(); std::cout << "File saved successfully." << std::endl; } else { std::cout << "Unable to save the file." << std::endl; } } }; int main() { std::string fileName; std::cout << "Enter the file name: "; std::cin >> fileName; TextEditor textEditor(fileName); int choice; std::string content; do { std::cout << "\n1. Open File\n2. Save File\n3. Exit\n"; std::cout << "Enter your choice: "; std::cin >> choice; switch (choice) { case 1: textEditor.openFile(); break; case 2: std::cout << "Enter the content to save: "; std::cin.ignore(); // Ignore newline character in buffer std::getline(std::cin, content); textEditor.saveFile(content); break; case 3: std::cout << "Exiting the text editor." << std::endl; break; default: std::cout << "Invalid choice. Please try again." << std::endl; } } while (choice != 3); return 0; }