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:
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.