In: Computer Science
Add an item to a Text File / C++
the program will prompt for a filename AND then prompt for a text file item. text file items always contain an unknown amount of spaces, (see getline).
Allow the user to put both the filename and the extensions, like groceries.txt or retirementToDo.clist
Don't add any directory information to the filenames, use them as typed.
If the file does exist, the item will be APPENDED to the end of the file.
If that file does not exist, it will be created. (This will happen anyway with append)
The user may put in a checklist item with any number of spaces. (use getline(), not >>)
Attached the code. It has comments for explanation, you should go through them. If you get any queries, feel free to talk about it.
Program Screenshot for Indentation Reference:
Sample Output:
./fileitem
Enter filename: checklist.txt
Enter item to add: Finish web project by tomorrow
./fileitem
Enter filename: checklist.txt
Enter item to add: Get membership for gym
cat checklist.txt
Finish web project by tomorrow
Get membership for gym
Program code to copy:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// ask for filename
string filename;
cout << "Enter filename: ";
cin >> filename;
// open file stream is append mode
fstream file(filename, ios::in | ios::out |
ios::app); // ios::app is for append
// check file opened or created
if (!file) {
cout << "Unable to
access file" << endl;
return -1;
}
// get item to add
string item;
cout << "Enter item to add: ";
// ignore newlines in input buffer
cin.ignore(1, '\n');
getline(cin, item); // use getline
// add to the file
file << item << endl;
// close file
file.close();
return 0;
}