【问题标题】:How do I put in a fstream file into a Header File through C++如何通过 C++ 将 fstream 文件放入头文件
【发布时间】:2018-02-05 07:37:24
【问题描述】:

我在 C++ 中使用 fstream,它通过 main() 函数工作得很好。当我尝试使用头文件和相同的简单程序时,它不起作用。我想我需要在头文件中使用引用变量参数,但我只是不确定如何编写代码。可以这样写,让main函数去头文件取数据吗?

主要功能

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>

#include "Prog_5_15.h"

using namespace std;

int main()
{
    cout << "Hi Reed";
    //I would like to try to keep the data in 
    //the Header File

    //This works right
    ofstream outputFile;
    outputFile.open("e:\demofile2.txt");

    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    outputFile << "Beethoven\n";
    outputFile << "Mozart\n";
    outputFile << "Schubert\n";

    outputFile.close();

    // Can I put a function here from the Header File
    // that gets info from fstream? 
    // Write_This();  ??
    cin.get();

    return 0;
}

头文件

#pragma once

#ifndef P515_h
#define P515_h


class Prog_5_15
{
public:
    Prog_5_15();
    ofstream outputFile2;
    outputFile2.open("e:\demoFile3.txt");
    outputFile2.close();
    void Write_This();    // This part needs do be re-written
    ~Prog_5_15();
};

#endif // !P515_h
#include <iostream>
#include "Prog_5_15.h"

using namespace std;

Prog_5_15::Prog_5_15()
{
}

void Prog_5_15::Write_This()  // This needs to be re-written I think
{
    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    outputFile << "Beethoven\n";
    outputFile << "Mozart\n";
    outputFile << "Schubert\n";
}

Prog_5_15::~Prog_5_15()
{
}

【问题讨论】:

  • 获取一本 C++ 书籍并阅读有关类/对象的知识。
  • 确实有很多需要重写的地方,但是你错了。
  • 使用一种包含保护,而不是同时使用 #define 保护和 #pragma 一次

标签: c++ file reference header fstream


【解决方案1】:

在你的班级使用相同的名字。

class Prog_5_15
{
public:
    Prog_5_15();
    ofstream outputFile2;
    ...

void Prog_5_15::Write_This()
{
    cout << "Now writing data to the file\n";
    outputFile << "Bach\n";
    ...

您不能拥有outputFileoutputFile2。选择一个名字并坚持下去。

使用构造函数打开文件

Prog_5_15::Prog_5_15()
{
    outputFile.open("e:\\demoFile3.txt");
}

还要注意"e:\demoFile3.txt" 是错误的,如果你想在字符串中使用反斜杠,你必须使用\\

删除不需要的析构函数和文件关闭语句。如果您的教授告诉您不同,他们不知道他们在说什么。

尝试一下,当您有更多问题时再回来。读一本关于 C++ 的书,这是基本的东西,任何书都会涵盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多