Adding lines at the end of a file in c++ problem

Can someone tell me why the program is not working? Mainly the program is for adding new lines at the end of a file in c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   fstream f;
    int itemnumber,availability,n;
    string author,title;
    f.open("file.txt",ios::ate);
    cout<<"Enter the number of additional books: ";
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cout<<"Enter item number: ";
        cin>>itemnumber;
        cin.get();
        cout<<"Enter title: ";
        getline(cin,title);
        cout<<"Enter author: ";
        getline(cin,author);
        cout<<"Enter availability:";
        cin>>availability;
        f<<itemnumber<<" "<<title<<", "<<author<<", "<<availability<<endl;
    }
    f.close();
Before you write to a stream you should check that it is in a proper state.
1
2
3
4
5
6
  f.open("file.txt",ios::ate);
  if (!f)
  {
     perror(nullptr); // include <cstdio>
     return errno;
  }

Also have a look at the open modes: http://www.cplusplus.com/reference/fstream/fstream/open/
It gave me these 3 errors although I included <cstdio>
error: 'nullptr' was not declared in this scope
error: 'error' was not declared in this scope
error: return-statement with a value, in function returning 'void' [-fpermissive]|
nullptr is available since c++11. What compiler do you use ?
If your function is void then replace line 5 with return;
Yes it is void so you mean to replace the cout<<"Enter the number of additional books: "; with return am I right?
No, I meant like this.
1
2
3
4
5
6
  f.open("file.txt",ios::ate);
  if (!f)
  {
     perror(nullptr); // include <cstdio>
     return;
  }
Topic archived. No new replies allowed.