文件操作(OOP) [英] File Operations (OOP)
本文介绍了文件操作(OOP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
您需要寻找结束写入之前的文件,请参阅 http://www.cplusplus.com/reference/ostream/ostream/seekp/ [ ^ ]
所以你的电话会是这样的:
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:
if (myfile.is_open())
{
myfile.seekp(0, ios_base::end); //Seek to end of file.
cout << "Enter the title of the new show: ";
或者,当您使用以下重载打开文件时,可以执行此操作:
Alternatively, you can do this when you open the file with the following overload:
std::ofstream myfile ("shows.txt", std::ofstream::app);
这篇关于文件操作(OOP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文