注册 登录
编程论坛 C++教室

无法把数据保存进文件

qq4056 发布于 2015-06-05 00:34, 2034 次点击
程序代码:

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <iterator>
#include <fstream>
#include <string>
class StoreQuote
{
public:
    string quote, speaker;
    ofstream fileOutput;

    StoreQuote();
    ~StoreQuote();

    void inputQuote();
    void inputSpeaker();
    bool write();
};

//创建文件,并且打开
StoreQuote::StoreQuote()
{
    fileOutput.open("text.txt", ios::app);
}

//关闭文件
StoreQuote::~StoreQuote()
{
    fileOutput.close();
}

//输入文本
void StoreQuote::inputQuote()
{
    getline(cin, quote);
   //cin >> qsort >> endl;
}

void StoreQuote::inputSpeaker()
{
    getline(cin, speaker);
}

bool StoreQuote::write()
{
    if(fileOutput.is_open())
    {
        fileOutput << quote << "|" << speaker << "\n";
        return true;
      
    }
    else
    {
        return false;
    }
}



int main()
{
    StoreQuote quote;

    cout << "请输入一句话: " << endl;
    quote.inputQuote();

    cout << "请输入作者: " << endl;
    quote.inputSpeaker();

    if( &StoreQuote::write)
    {
        cout << "成功写入文件!" << endl;
    }
    else
    {
        cout << "写入文件失败!" << endl;
        return 1;
    }


    return 0;
}


麻烦大家帮忙看一下问题在哪,谢谢大家!
6 回复
#2
rjsp2015-06-05 08:20
首先,你这代码编译失败。算了,不说。

if( &StoreQuote::write) 应当是 if( quote.write() ),这也错得太离谱了吧
#3
qq40562015-06-05 09:31
回复 2楼 rjsp
在window7下 用visual studio2012编译的结果,并且无错误,只是输入数据无法保存
#4
qq40562015-06-05 09:33
回复 2楼 rjsp
开始我是用  if( quote.write() ) 但是编译报错。
#5
小码农2015-06-05 10:25
用这个if( quote.write() ) ,才是对象调用函数的正确方法。
之所以编译失败,我觉得是你用了cout<<和file<<,但却没有使用命名空间,在预编译处加上using namespace std;  亲测可以

[ 本帖最后由 小码农 于 2015-6-5 10:51 编辑 ]
#6
qq40562015-06-05 21:23
回复 5楼 小码农
using namespace std;这句话有了,编译没有错误,正常运行,但是不能把数据写入text.txt,程序运行结束之后我打开text.txt是空的。
#7
qq40562015-06-05 21:27
问题已经解决了,谢谢rjsp和小码农,你们是对的,是我粗心。谢谢!
1