Disclosure: I am a student right now, so if you see any bad habits in my code, feel free to point them out. I have questions about both the ofstream
and ifstream
portions of my code.
In the ofstream
, the user can create their own shopping list and name it (which will end up being the file name). Once their list is created, the file will save with the data.
Here my question: How do I automatically assign a file type to a file a user named? Here is my current code for it:
void createList(double price[100], double quantity[100], string item[100], double tax, int list_size) {
ofstream saved_list;
string listname;
string fileApplicator = ".txt";
cout << "What would you like to save this list as?: ";
getline(cin, listname.append(fileApplicator));
saved_list.open(listname.c_str());
As for the ofstream
part of my code, I want the user to be able to select which file they want read based on the name of the file.
Here's my question: When I run the code, the file fails to open every time. I have a current file saved as safeway.txt but it will not open when I attempt it. Here is the code for it:
void reviewList(void) {
ifstream saved_list;
string listname;
string fileApplicator = ".txt";
char viewAnother = 'Y';
do {
cout << "Which list would like to open: ";
getline(cin, listname.append(fileApplicator));
saved_list.open(listname.c_str());
if (saved_list.is_open()) {
......//other code
}
cout << "Would you like to view a different list (Y/N): ";
cin >> viewAnother;
viewAnother = toupper(viewAnother);
if (viewAnother == 'N')
break;
}
else {
cout << "List not found. Please try again.\n";
}
} while (viewAnother == 'Y');
}