Im supposed to write a program that asks the user to input a a song title and stores it into a file. the other functions are to print the most recently added song and to show the list of all available songs. so:
Music index
1. add new song to file
2. print most recent song in file
3. display all songs in file
4. quit
I understand to do this i need to use switches and cases. what i need help with is number 1 and 2 in the list above. here is my current code:
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
using std::string;
int main () {
fstream inputfile;
string name[4];
int choice;
do{
cout<<"\n Music index list";
cout<< "\n 1. Add a new song to the file";
cout<< "\n 2. Print the most recently added song in the file";
cout<< "\n 3. Display all songs in the file";
cout<< "\n 4.Quit";
cin>> choice;
switch (choice) {
case 1:
inputfile.open("music.txt");
cout<< "What is the name of the song? ";
for (int x = 0; x <= 4; x++){
cin>> name[x];
inputfile << name[x];
inputfile.close;
break;
case 2:
inputfile.open()
getline (inputfile, name);
cout << name << endl;
First problem string name[4];
you planned to support only four entries in the file.
So if you want to keep it that way than the last song is always going to be name[3];
I'm sorry i made the program more complicated than it needed to be. the file should already exist. how do i go about printing the last line in the file added (my third song)t? this is my new code:
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main () {
fstream inputfile;
int choice;
inputfile.open("music.txt");
inputfile << "my first song\n";
inputfile << "my seond song\n";
inputfile.close();
do{
cout<< "\n Music index list";
cout<< "\n 1. Add songs to the file";
cout<< "\n 2. Print the most recently added song in the file";
cout<< "\n 3. Display all songs in the file";
cout<< "\n 4. Quit";
cin>> choice;
switch (choice) {
case 1:
cout<< "What is the new title?";
inputfile.open("music.txt", ios::out | ios:: app);
inputfile<< " my third song\n";
inputfile.close();
break;
I dont need to know how to display all songs or quit; those i already have ready to add in as soon as im done figuring out how to get the last line from the file.