Journal Entry
Write a program that opens a file named journal_entries.txt in append mode and adds new content without overwriting the existing data. The program should prompt the user to enter the current date and then the journal entry.
Hint
- Open the file in append mode (
std::ios::app) to ensure new data is added to the end.
Answer
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string filename = "journal_entries.txt";
// Open the file in append mode
std::ofstream outFile(filename, std::ios::app);
if (!outFile) {
std::cerr << "Error: Could not open the file " << filename << "." << std::endl;
return 1;
}
// Get the current date and journal entry from the user
std::string currentDate, journalEntry;
std::cout << "Enter the current date (e.g., 2024-08-04): ";
std::getline(std::cin, currentDate);
std::cout << "Enter your journal entry: ";
std::getline(std::cin, journalEntry);
// Append the date and journal entry to the file
outFile << currentDate << "\n" << journalEntry << "\n" << std::endl;
std::cout << "Your journal entry has been added." << std::endl;
outFile.close();
return 0;
}