writing to a text file

i want to write to a text file without overwriting what is already there. i also want to write it on the next line down, which shouldn't be hard once i figure out how to write to it.

this is what i have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cout << "What is the name of your supply that you want to add? ";
    cin >> addsupply;
    cout << "How many are there? ";
    cin >> addsupplynum;
    ifstream supplies ("supplies.txt");
    if (sup.is_open())
    {
        while (sup.eof())
        {
            getline (sup,addsupply);
            cout << addsupply << ": " << addsupplynum;
        }
        sup.close();
        cout << "supply added" << endl << endl;
    }
    else
    {
     cout << "Could not open file";
    }


all that happens is it says supply added but when i open the text file nothing is there.
Don't loop on fstream::eof(). (It can cause an infinite loop.) Also, I think you want to loop while not EOF.
[edit]
Oh, I suppose I should tell you what you should loop on: fstream::good().
1
2
string s;
while (getline( supplies, s ).good()) ...
The .good() part can be omitted.
[/edit]

Once you find EOF, you must fstream::clear() the error state so that it becomes writable.

Finally, you cannot write output to an input stream.

You can avoid it all just by seeking to EOF when you open it:
1
2
3
4
fstream supplies( "supplies.txt" );
supplies.seekp( 0, ios::end );
supplies << "Hello world!\n";
supplies.close();


Hope this helps.
Last edited on
thanks for the Duoas it works.

but now i want to read from it. and when i do it stops at the first space.

this is my code.

1
2
3
4
5
6
7
8
ifstream sup;
    sup.open("supplies.txt");
    if (sup.is_open())
    {
        sup >> revsupply;
        sup.close();
    }
    cout << revsupply << endl;
Last edited on
Open the file with ("supplies.txt",std::ios::append)
On line 11, which I'm guessing is when you intend to write to the file, you're not doing it. You're just sending output to std::cout. Replace the cout with supplies.
Oh, and supplies should be an std::ofstream, not std::ifstream, since you're going to be using it for output, not input.
Remember the rule: to memory is input, from memory is output.

EDIT: Gah! Too slow.
Last edited on
how about just opening it with ios::app?^^...


[edit]...lol fail, too late :D
Last edited on
Topic archived. No new replies allowed.