前言:
参考:B站UP主鱼C_小甲鱼<C++快速入门>
代码调试平台:VS2017,调试成功。
问题描述:
问题描述:输入一句名言,并写入文件。
代码实现:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class StoreQuote
{
public:
string quote, speaker;
ofstream fileoutput;
StoreQuote();
~StoreQuote();
void inputquote();
void inputspeaker();
bool write();
};
StoreQuote::StoreQuote()
{
fileoutput.open("test.txt", ios::app);
}
StoreQuote::~StoreQuote()
{
fileoutput.close();
}
void StoreQuote::inputquote()
{
getline(cin, quote);
}
void StoreQuote::inputspeaker()
{
getline(cin, speaker);
}
bool StoreQuote::write()
{
if (fileoutput.is_open())
{
fileoutput << quote << "|" << speaker << "\n";
return 1;
}
else
{
return 0;
}
}
int main()
{
StoreQuote quote;
cout << "请输入一句名言:" << "\n";
quote.inputquote();
cout << "请输入作者:" << "\n";
quote.inputspeaker();
if (quote.write())
{
cout << "成功写入文件!";
}
else
{
cout << "文件写入失败!";
}
return 0;
}