How would you prevent it from writing over a line in a file? For example, whenver I run this program and type multiple things in, in just keeps on writing over the same line, instead of making a new one for each input. Can somebody show me how to prevent this?
#include %26lt;iostream%26gt;
#include %26lt;stdlib.h%26gt;
#include %26lt;string%26gt;
#include %26lt;cstdlib%26gt;
#include %26lt;fstream%26gt;
using namespace std;
int main()
{
cout %26lt;%26lt; "Please enter the person whom you are voting for." %26lt;%26lt; endl;
string name;
cin %26gt;%26gt; name;
if (name == "exit") {
return 0;
}
else {
ofstream outfile("votinglog.txt");
outfile %26lt;%26lt; name %26lt;%26lt; "\n" %26lt;%26lt; endl;
cout %26lt;%26lt; "Thank you, your vote has been received. \a " %26lt;%26lt; endl;
outfile.close();
return main();
}
}
In C++, how would you prevent it from writing over a line in a file?
Look at http://www.cplusplus.com/reference/iostr... . You'll see that you want to open up the file for appending. Hence, you should do something like outfile("votinglog.txt", ios::app)
Other remarks:
- #include %26lt;stdlib.h%26gt; - Deprecated. The correct form is %26lt;cstdlib%26gt; . Which you did anyway. So why %26lt;stdlib.h%26gt;?
- return main(); - What is this supposed to be? An attempt at a recursive function? You never call main. It is a special function, defined as an entry point. If you want a loop, use a while loop, set to a condition of true.
And when posting code, use http://www.rafb.net/paste/ or another nopaste / pastebin.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment