简体   繁体   中英

C++ create ifstream/ofstream in a class, associated with pre-made text file

I am having a problem associating an ifstream read and ofstream print to a pre-made text file called finances.txt. This is within a class called Data . So far, this is what I've tried:

I declared ifstream read and ofstream print in the class header file. Then, in the cpp file:

Data::Data(string n, string d)
:name(n),
date(d)
read(name)
print(name)
{
    cout << "name = " << name << endl;
    read.open(name);
    print.open(name);
    //...
}

I also tried this, without declaring anything in the header:

Data::Data(string n, string d)
:name(n),
date(d)
{
    ifstream read(name);
    ofstream print(name);
    //...

And just different variations of this kind of thing. The syntax is always correct in the sense that I don't get any errors, but whenever it runs, it acts like the file doesn't exist and creates a new one named finances.txt , which in turn erases all of the text that was in the original. I have done this correctly before and just can't remember what I did and what I am doing incorrectly here.

I am a little confused as to what exactly you are trying to do? Are you trying to append to the file? Because when you call ofstream print(name) you are writing over the file that you are reading in.

So if you want to append to that same file you have to add. fstream::app in the declaration of the ofstream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM