Click here to Skip to main content
15,899,126 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
if(choice ==3){
        string title = "";
        ofstream myfile ("shows.txt");
        if (myfile.is_open())
        {
            cout << "Enter the title of the new show: ";
            cin >> title;
            
            myfile << title << endl;
            myfile.close();
        }
        else cout << "Operation Failed";
  }


When I ask the user to enter the name of a new show, it iss automatically placed at the beginning, over-writing whatever value is in the first line. How do I add a new line at the bottom of the text file, then add the user's input to that line?
Posted

1 solution

You need to seek to the end of the file before writing to it, see http://www.cplusplus.com/reference/ostream/ostream/seekp/[^]

So your call would look something like:

C++
if (myfile.is_open())
        {
            myfile.seekp(0, ios_base::end);    //Seek to end of file.
            cout << "Enter the title of the new show: ";


[Edit]

Alternatively, you can do this when you open the file with the following overload:

C++
std::ofstream myfile ("shows.txt", std::ofstream::app);
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 27-Dec-13 22:45pm    
5ed. It looks like you ignored the OP's requirement to open a new line for a user to input, but not doing so is actually better.
—SA
Ron Beyer 27-Dec-13 22:49pm    
Thanks, I figured the wording was off, and he didn't mean put a blank line and then the data, but to insert a slot for new data, which isn't necessary if you are just appending to the end of the file.
Sergey Alexandrovich Kryukov 27-Dec-13 22:55pm    
Sure.
—SA
Member 10436484 27-Dec-13 22:50pm    
I went with the second solution which works perfectly. I think there was a slight error with the first. Thank you for your assistance.

-Kevin.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900