What is going wrong in this program?

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
#include <iostream>
#include <fstream>
using namespace std;
int b;
class book
{
private:
    int bookno;
    char booktitle[100];
    float price;
    float total_cost(int);
public:
    void input();
    void purchase();
    void display();
};
void book::input()
{
    cout<<"\nEnter book number:";
    cin>>bookno;
    cout<<"\nEnter book title:";
    cin.getline(booktitle, 100);
    cout<<"\nEnter price:";
    cin>>price;
}
void book::purchase()
{
    float p;
    cout<<"\nEnter no. of copies:";
    cin>>b;
    p=total_cost(b);
    cout<<"\nTotal cost:"<<p;
}
float book::total_cost(int x)
{
    return price*x;
}
void book::display()
{
    cout<<"\n\n\nBook number:"<<bookno;
    cout<<"\nBook title:"<<booktitle;
    cout<<"\nPrice:"<<price;
    cout<<"\nTotal cost:"<<total_cost(b);
}
int main()
{
    book s[2], t[2];
    fstream fs("Book.dat",fstream::in|fstream::out|fstream::binary);
    cout<<"\n\nEnter details:";
    for (int i=0;i<2;i++)
    {
        s[i].input();
        s[i].purchase();
        fs.write((char *)&s[i], sizeof(s[i]));
        fs.read((char *)&t[i], sizeof(t[i]));
    }
    fs.close();
    cout<<"\n\n\n\nDetails:";
    for (int i=0;i<2;i++)
    {
        t[i].display();
    }
    return 0;
}


output:
Enter details:
Enter book number:89

Enter book title:
Enter price:450

Enter no. of copies:2

Total cost:900
Enter book number:74

Enter book title:
Enter price:63

Enter no. of copies:2

Total cost:126



Details:


Book number:2424048
Book title:
Price:6.69737e-039
Total cost:1.33947e-038


Book number:0
Book title:
Price:0
Total cost:0



Input for book titile is not at all allowed as the input doen't even go there.
Last edited on
1
2
3
4
    cout<<"\nEnter book number:";
    cin>>bookno;
    cout<<"\nEnter book title:";
    cin.getline(booktitle, 100);
`getline()' stops at end of line, you press an <Return> after inputting the book number, so you get an empty string as the name.
you may cin.ignore() after using >>

Apart
1
2
fs.write((char *)&s[i], sizeof(s[i]));
fs.read((char *)&t[i], sizeof(t[i]));

http://stackoverflow.com/questions/14329261/are-seekp-seekg-interchangeable
you are at the end of the file, have nothing to read. See how «Details» gives you garbage.
After you get the book number there is '\n' left in the input buffer.

The next getline receives this '\n' as input and returns an empty string.

Insert another getline to remove the '\n'.

1
2
3
4
5
6
7
8
9
10
void book::input()
{
    cout<<"\nEnter book number:";
    cin>>bookno;
    cin.getline(booktitle, 100); ////        
    cout<<"\nEnter book title:";
    cin.getline(booktitle, 100);
    cout<<"\nEnter price:";
    cin>>price;
}

Last edited on
Topic archived. No new replies allowed.