Making a program that writes to a file

I need help with this because it's time for my project(this is the first program from my project) and I'm having difficulties cause we never really worked with files in school..
Basically, I have to make a program that writes objects from a class to a file.
I created the class, but am a tad clueless as to how I should proceed with the writing..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Song_By_Rock_Band
{
	private:
		 string song1;
		 string rock_band;
		 string time_song1;

	public:
		 Song_By_Rock_Band(string song, string the_band, string time);

		 void write_in_file();
};

Song_By_Rock_Band::Song_By_Rock_Band(string song, string the_band, string time)
{
	song1=song;
	rock_band = the_band;
    time_song1 = time;
}

void Song_By_Rock_Band::write_in_file()
{
    int n;
struct pesn
{
	char   song[30];
	char   band[20];
	float  time;
};
pesn pesni[15];
pesn *q;
q=pesni;
cout<<"How many songs would you like to enter(n <=15 )";
cin>>n;
    for(int i=0;i<n;i++)
{
	cout<<"song name:";
	cin>> q->song;
	cout<<"group name :";
	cin>> q->band;
	cout<<"enter lenght of song :";
	cin>> q->time;
	q++;
}
q=pesni;
for( int i=0; i<n; i++)
{

  ofstream f;
  f.open ("rock_band.txt", ios::out);
  f << "Song- " << q->song << endl;
  f << "Rock Band- " << q->band << endl;
  f << "Time- " << q->time<<endl;
  f << "------------"<<endl;
  q++;
  f.close();
}
}
int main()
{
Song_By_Rock_Band rock_band("Thunderstruck", "AC/DC", "04:54");

rock_band.write_in_file();
return 0;
}

   


It works..sort of but whenever you enter more than one song, it overwrites the previous.

Help me, please.
Last edited on
Replace ios::out with ios::app, which will append to the end of the file rather than overwrite it.
Silly me, thanks for the solution..

Now there's a different problem - when you enter the details of a song, the program gets bugged when you use an interval like if for example the song is Bohemian Rhapsody, it bugs messes up the writing to the text.
To read a complete line, use std::getline() http://www.cplusplus.com/reference/string/string/getline/

Change all your input operations from std::cin >> ... to std::getline( std::cin, ... ).
It is easier if you don't mix formatted input with unformatted input.

1
2
3
4
5
6
7
8
9
10
	// cin>> q->song;
        getline( cin, q->song ) ;

	cout<<"group name :";
	// cin>> q->band;
        getline( cin, q->song ) ;

	cout<<"enter lenght of song :";
	// cin>> q->time;
        getline( cin, q->time ) ;


Topic archived. No new replies allowed.