working with files in Class

hi all
in second func(output)
i want to cout amount variable(that was saved in text.txt) but only "0" will print
:(


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
  #include <fstream>

using namespace std;

class calcu{

public:

    void input();

    void output();

private:

    int amount;

    string name;



};

void calcu::input(){

    cout<<"Enter:"<<endl;

    cin>>amount>>name;

    ofstream my("e:/test.txt");

    my<<name<<"  "<<amount;

}

void calcu::output(){

    cout<<"The Result is :"<<endl;

    ifstream my;

    my.open("e:/test.txt");

    my>>amount>>name;

    cout<<name<<" "<<amount;

}



int main()

{

    calcu run;

    run.input();

    run.output();

}
Check to make sure your test.txt file is actually being created. Usually in the root directory on a drive, you need admin access to create a file -- which your program probably doesn't have. So creating the file is failing in your input function. Then when you try to read the file, you fail, which fills your vars with 0 when you try to read.


Try getting rid of the absolute path, here. Just save/load "test.txt" instead of "e:/test.txt"
Change line 43 from:
 
    my >> amount >> name;
to
 
    my >> name >> amount;


Also, depending on the way the compiler handles failed stream input, the previous values stored in amount and name may remain, thus if the file access fails completely, the apparently correct output might be printed. you can check for this,
45
46
47
48
    if (my)
        cout << name << " "<< amount;
    else
        cout << "File input error";
Last edited on
Topic archived. No new replies allowed.